Install mongoose
Use express to prepare a TestMongoDB project. The command sequence is as follows:
express TestMongoDB cd TestMongoDB npm install
After executing the above command, use the following command to install mongoose:
npm install mongoose --save
This command will install mongoose and use it as a dependency of the project, and the MongoDB driver and regexp modules that mongoose depends on will also be automatically installed.
Example
Using mongoose, you can create a new database, create a new collection, and perform CRUD operations on the documents in the collection. When writing code, you can verify whether the results meet expectations against the mongo shell.
Create a new mongo.js file under TestMongoDB with the following content:
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'); }); });
For the above file, directly execute the "node mongo.js" command to see the effect.
To use mongoose, first require, and then use the connect method to connect to the database. connect prototype:
connect(uri, options, [callback])
The format of uri is similar: "mongodb://user:pass@localhost:port/database".
Mongoose’s connection object defines some events, such as connected, open, close, error, etc. We can monitor these events.
In our sample code, I listened to the open event, defined the Schema in the callback function, and called mongoose.model to compile the Schema and obtain the Model object. It should be noted that the collection name specified when defining Schema must be consistent with the first parameter of mongoose.model.
After getting the Model object, you can perform operations such as addition, deletion, modification, and query. The Model object has methods such as find(), findOne(), update(), and remove(), which are similar to how we use them in the mongo shell. These methods have an optional callback. When you provide these callbacks, the execution results will be returned to you through this callback. If you do not provide it, these methods will return a Query object. You can assemble new options through Query, and then call Query's exec (callback) to submit the query.
I used callback instead of Query when searching for WangEr’s files in the code.
The Model object has a Model(doc) method, which is used to construct a document. When creating a Lisi document, the save() method of this Document object can save the document to the database.
Basic operations via mongoose:
1. Added
var obj = new Movie(); obj.title = '标题一'; obj.content = '内容'; obj.save(function(err) { });
2. Delete
Movie.remove({ _id:id },function (err) { })
3. Change
Movie.update({ _id:id },json,{},function (err) { })
4. Check
Movie.findOne({ _id: id }, function(err, obj) { }); Movie.find({}).sort({_id: -1}).limit(3).exec(function(err, obj) { })