Mongoose installation with Node.js operation MongoDB basic tutorial

  • 2021-01-18 06:15:44
  • OfStack

Install mongoose

Use express to prepare an TestMongoDB project with the following command sequence:


express TestMongoDB
cd TestMongoDB
npm install

After executing the above command, use the following command to install mongoose:


npm install mongoose --save

This command installs mongoose as a project dependency, and modules that mongoose depends on, such as MongoDB, driver and regexp, are automatically installed.

The instance

With mongoose, you can create a new database, create a new collection, and perform CRUD operation on the documents in the collection. When writing code, you can verify whether the results meet expectations against mongo and shell.

Create a new mongo.js file under TestMongoDB with the following contents:


var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/accounts');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
 console.log('mongoose opened!');
 var userSchema = new mongoose.Schema({
   name:{type: String, unique: true}, 
   password:String
  }, 
  {collection: "accounts"}
  );
 var User = mongoose.model('accounts', userSchema);

 User.findOne({name:"WangEr"}, function(err, doc){
  if(err) console.log(err);
  else console.log(doc.name + ", password - " + doc.password);
 });

 var lisi = new User({name:"LiSi", password:"123456"});
 lisi.save(function(err, doc){
  if(err)console.log(err);
  else console.log(doc.name + ' saved');
 }); 
});

The above file, directly execute "node mongo. js" command can view the effect.

To use mongoose, start with require and then connect to the database using the connect method. connect prototype:


connect(uri, options, [callback])

The format of uri is similar: "mongodb://user:pass@localhost:port/database".

The connection object of mongoose defines a number of events, such as connected, open, close, error, etc. We can listen on these events.

In our example code, I listen for the open event. In the callback function, I define Schema and call mongoose.model to compile Schema to get the Model object. It is important to note that the collection name specified when Schema is defined is identical to the first parameter of mongoose.model.

Once you have the ES75en object, you can add, delete, modify, search, and other operations. ES76en objects have methods find(), findOne(), update(), remove(), and so on, similar to how we use them in ES81en and ES82en. Each of these methods has an optional callback, and when you provide these callback, the results of the execution will be returned to you through this callback. If you don't, these methods will return an ES86en object, and you can assemble new options from ES87en and then call ES89en (ES90en) from ES88en to submit the query.

I used callback instead of Query when looking for WangEr files in the code.

The Model object has an Model(doc) method that constructs one document (Document). It is the save() method of the Document object that saves the document to the database when creating a document for Lisi.
Basic operation with mongoose:
1,


var obj = new Movie();
obj.title = ' The title 1';
obj.content = ' content ';
obj.save(function(err) {
  
});

2, delete


Movie.remove({
  _id:id
},function (err) {
  
})


3, change


Movie.update({
  _id:id
},json,{},function (err) {
  
})


4,


Movie.findOne({
  _id: id
}, function(err, obj) {
 
});
Movie.find({}).sort({_id: -1}).limit(3).exec(function(err, obj) {
 
})


Related articles: