Node. js MongoDB driver Mongoose basic usage tutorial _ node. js

Source: Internet
Author: User
Tags findone mongodb driver
This article mainly introduces Node. the basic usage tutorial of MongoDB driver Mongoose of js, front-end js + back-end Node. js + database MongoDB is a popular full-stack JavaScript development solution. If you need it, you can refer to the following mongoose to make better use of the mongodb database, without the need to write tedious business logic.

Install

npm install mongoose

Initialization
Before using mongoose, you need to install node and mongodb. Here we will not talk about how to install node and mongodb.

Var mongoose = require ("mongoose"); var Schema = mongoose. schema; var db = mongoose. connection; mongoose. connect ('mongodb: // localhost/animal '); db. on ('error', console. error); db. once ('open', function () {// create the mode and model here}

Quick Start
In mongoose, all data is in one mode. Each mode is mapped to the mongodb set and the file structure of the set is defined.

// Create an animal mode. All animals have all the attributes var animalSchema = new Schema ({name: String, age: Number,}) in this mode ,});

A model is a variety of constructor defined from the Schema. Model instances can use a lot of operations. The creation and retrieval of all documents are handled by the model.

 var animalMode = db.model('Animal', animalSchema);

An instance of a model is essentially a file, which can be easily created or modified.

Var cat = new animalMode ({name: 'catname', age: '7', // strings are still used here, And mongoose will automatically convert the type}); cat. save (function (err, thor) {if (err) return console. log (err); console. log (thor) ;}); // or you can use create // cat. create (function (err, thor) {// if (err) return console. log (err); // console. log (thor); //}); // execute the following command to find animalMode. find (function (err, people) {if (err) console. log (err); console. log (people) ;}); // search for the Qualified Data animalMode. findOne ({title: 'catname'}, function (err, cat) {if (err) console. log (err); console. log (cat );});

Schema
Data Type

This is all the data types in the Schema, including the mongoose custom data types.

  • String
  • Number
  • Date
  • Buffer
  • Boolean
  • Mixed
  • ObjectId
  • Array

Use of each data type

 var animalMode = mongoose.model('Animal', schema); var cat = new animalMode; cat.name = 'Statue of Liberty'    //String cat.age = '7';        //Number cat.updated = new Date;      //Date cat.binary = new Buffer(0);     //Buffer cat.living = false;       //Boolean cat.mixed = { any: { thing: 'i want' } }; //Mixed     cat._someId = new mongoose.Types.ObjectId; //ObjectId cat.ofString.push("strings!");    //Array

Mixed is a Mixed type customized by mongoose. Because Mixed does not define specific content, you can use {}. The following two definitions are equivalent.

 var animalSchema = new Schema({any: {}}); var animalSchema = new Schema({any: {Schema.Types.Mixed}});

Custom Method

You can bind a method to a Schema.

 var animalSchema = new Schema({  name: String,  age: Number, }); animalSchema.methods.findSimilarTypes = function (cb) {  return this.model('Animal').find({ name: this.name }, cb); } var animalMode = db.model('Animal', animalSchema); cat.findSimilarTypes(function(err, cat){  if(err) console.log(err);  console.log(cat); });

You can also add static methods for the Schema.

 animalSchema.statics.findByName = function (name, cb) {  return this.find({ name: new RegExp(name, 'i') }, cb); } var animalMode = db.model('Animal', animalSchema); animalMode.findByName('catName', function (err, animals) {  console.log(animals); });

Index

We can create indexes for mongodb data. mongodb supports secondary indexes. To improve data search and positioning, it is necessary to create a composite index.

 var animalSchema = new Schema({  name: String,  age: Number,  tags: { age: [String], index: true } // field level }); animalSchema.index({ name: 1, age: -1 }); // schema level

However, this index may have a significant performance impact. We recommend that you stop it in production and set the automatic index in the setting mode to false to disable it.

 animalSchema.set('autoIndex', false); // or new Schema({..}, { autoIndex: false });

Model
C

Cat. save (function (err, thor) {if (err) return console. log (err); console. log (thor) ;}); // or you can use create cat. create (function (err, thor) {if (err) return console. log (err); console. log (thor );});

R

// FindanimalMode. find (function (err, cat) {if (err) console. log (err); console. log (cat) ;}) // findOneanimalMode. findOne ({name: 'catname'}, function (err, cat) {if (err) console. log (err); console. log (cat) ;}) // findByID // same as findOne, but it receives the _ id of the document as a parameter and returns a single document. _ Id // It can be a string or ObjectId object. AnimalMode. findById (id, function (err, adventure) {if (err) else el. log (err); console. log (adventure) ;}); // where // regular animalMode is supported when the data type is string. where ('age', '2'cmd.exe c (function (err, cat) {if (err) console. log (err); console. log (cat) ;}); animalMode. where ('age '). gte (1 ). lte (10 ). where ('name', 'catname '). exec (function (err, cat) {if (err) console. log (err); console. log (cat );});

U
Updated function Model. update provided in the official documentation

Model. update (conditions, doc, [options], [callback])

  • Conditional Update conditions
  • Doc update content
  • Option update option
  • Safe (boolean) security mode. The default value is true.
  • Whether to create a new document when the upsert (boolean) condition does not match. The default value is false.
  • Whether multi (boolean) updates multiple files. The default value is false.
  • Strict (boolean) strict mode. Only one data record is updated.
  • Overwrite (boolean) overwrites data. The default value is false.
  • Callback
  • Returned value when an error occurs during data update in err
  • NumberAffected (I am not sure yet)
  • Number of affected lines in rawResponse

animalMode.update({name: 'catName'}, {age: '6'}, {multi : true}, function(err, numberAffected, raw){ if (err) return console.log(err); console.log('The number of updated documents was %d', numberAffected); console.log('The raw response from Mongo was ', raw);});

D

animalMode.remove({age: 6}, function(err){ if (err) console.log(err);})

Others
// Number of returned documents

animalMode.count({age: 2}, function(err, cat){ if (err) console.log(err); console.log(cat);})

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.