Home > Web Front-end > JS Tutorial > Basic tutorial on installing and using Mongoose with Node.js to operate MongoDB_node.js

Basic tutorial on installing and using Mongoose with Node.js to operate MongoDB_node.js

WBOY
Release: 2016-05-16 15:12:46
Original
1631 people have browsed it

Install mongoose

Use express to prepare a TestMongoDB project. The command sequence is as follows:

express TestMongoDB
cd TestMongoDB
npm install
Copy after login

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

npm install mongoose --save
Copy after login

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');
 }); 
});

Copy after login

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])
Copy after login

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) {
  
});
Copy after login

2. Delete

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


3. Change

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


4. Check

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template