Familiar with operating database

Use mongoose to operate mongoDB

npm install mongoose --save-dev
Copy the code

Create a new mongoose.js file and write the mongoose code

/* mongoose.js: establish database connection */
var mongoose = require('mongoose') / / into the mongoose
var url = "mongodb://localhost:27017/back-table-db"; // Local database address
mongoose.connect(url)

// connect() returns a pending connection, which can be used to determine whether the connection succeeded or failed
var db = mongoose.connection; 
db.on('error'.console.error.bind(console.'connection error:'));
db.once('open'.function() {
  console.log("Successful connection to "+url)
});
Copy the code

After running $node mongoose. Js output: Successful connection to mongo: / / localhost: 27017 / back – table – db connection database Successful at this time.

Create Schema and write data

/* mongoose.js: insert data with mongoose.Schema */ to establish a database connection
var Schema = mongoose.Schema // All schemas are mapped to a MongoDB collection

let user = {
  name:String
}

var userSchema = Schema(user)
var User = mongoose.model('User', userSchema); // Compile the schema into the model constructor

var newUser = new User({name: "yyyyyyyyyyyy"})// Mongoose will automatically find a collection whose name is the plural of the model name
newUser.save()
Copy the code

After running $node mongoose.js, you can use Adminmongo to check whether data is added successfully, or you can use terminal command to check whether data is added successfully.

Express Service Framework [preliminary]

Mongoose just helps us connect to the data and read and write it. We also need to start a service framework that encapsulates Node’s HTTP services.

Create server.js application Demo and start the service interface:

/* server.js: import express module, set route */
var express = require('express')()

express.get('/'.function (request, response) { / / routing
  response.send("hello world!") // Pass the HTTP response
})
express.listen(3000) / / listening to port 3000, the default localhost: 127.0.0.1 | | 0.0.0.0
Copy the code

Run $node express.js, open a browser, and type http://localhost:3000/