Install and use Mongoose with Node. js to operate MongoDB.

Source: Internet
Author: User
Tags findone mongodb driver mongodb server mongo shell

Install and use Mongoose with Node. js to operate MongoDB.

Install mongoose

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

express TestMongoDBcd TestMongoDBnpm install

After running the preceding command, run the following command to install mongoose:

npm install mongoose --save

This command will install mongoose and use it as the project dependency, while mongoose's MongoDB driver and regexp modules will also be installed automatically.

Instance

Mongoose allows you to create a database, create a set, and perform CRUD operations on documents in the set. When writing code, you can check whether the mongo shell verification result meets expectations.

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

In the preceding file, run the "node mongo. js" command to view the effect.

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

connect(uri, options, [callback])

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

Mongoose's connection object defines some events, such as connected, open, close, and error. We can listen to 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 to get the Model object. Note that the collection name specified during Schema definition must be consistent with the first parameter of mongoose. model.

After obtaining the Model object, you can perform operations such as adding, deleting, modifying, and querying. Model objects include methods such as find (), findOne (), update (), and remove (), which are similar to the usage in mongo shell. Each of these methods has an optional callback. When you provide these callback, the execution result 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 exec (callback) to submit the Query.

I used callback when searching WangEr files in the code, and no Query is used.

The Model object has a Model (doc) method to construct a Document ). When you create a Lisi Document, the save () method of this Document object can save the Document to the database.
Basic mongoose operations:
1. Add

Var obj = new Movie (); obj. title = '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. Query

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

Articles you may be interested in:
  • Detailed description of Node. js environment configuration using MongoDB in Wondows
  • Install Node. js and mongodb notes on CentOS
  • Node. js and MongoDB implement a simple Log Analysis System
  • Node. js mongodb Operations Learning Summary
  • Address book based on AMAP location developed by AngularJS + Node. js + MongoDB
  • Interaction between mongodb databases with amazing node. js Reading Notes
  • Getting started with Node. js, Express, Ejs, Mongodb server and application development
  • Node. js instance for mongoDB operations
  • Using mongoskin in Node. js to operate mongoDB instances
  • Node. js MongoDB driver Mongoose basic usage tutorial

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.