Node.js's MongoDB drive Mongoose Basic use tutorial _node.js

Source: Internet
Author: User
Tags findone mixed mongodb mongodb collection install node mongodb support

Using mongoose allows us to better use the MongoDB database without having to write tedious business logic.

Installation

NPM Install Mongoose

Initialize the use of
before using mongoose, you need to install node and MongoDB, which do not talk about node and MongoDB installation methods.

 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 schema and model
 }

Quick Start
in Mongoose, all data is a pattern, each schema maps to a MongoDB collection, and the collection file structure is defined.

 Here an animal model is established, all animals have all the attributes of this pattern
 var animalschema = new schema ({
  name:string,
  age:number,
 });

Models are a variety of constructors that we define from schemas, examples of which can use many operations, and all document creation and retrieval is handled by the model

 var animalmode = Db.model (' Animal ', animalschema);

The actual instance of the model is a file, and we can easily create and modify this file

 var cat = new Animalmode ({
  name: ' CatName ', age
  : ' 7 ',//still use string here, Mongoose will automatically convert type
  });

 Cat.save (function (err, Thor) {
  if (err) return Console.log (err);
  Console.log (Thor);
 });
 Alternatively, you can use the Create
 //cat.create (function (err, Thor) {
 //if (ERR) return Console.log (err);
 Console.log (Thor);
 //});

 Performs
 a lookup animalmode.find (function (err, people) {
  if (err) console.log (err);
  Console.log (people);
 });
 Find eligible 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 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

Where mixed is a mixed type of mongoose customization, since mixed does not define specific content and can be used with {}, the following 2 defined forms are equivalent.

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

Custom Methods

You can bind a method for a schema

 var animalschema = new Schema ({
  name:string,
  age:number,
 });

 AnimalSchema.methods.findSimilarTypes = function (CB) {return
  This.model (' Animal '). Find ({name:this.name}, CB) c6/>}

 var animalmode = Db.model (' Animal ', animalschema);

 Cat.findsimilartypes (function (err, cat) {
  if (err) console.log (err);
  Console.log (cat);
 };

You can also add a static method to a 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 index MONGODB data, MONGODB support Level Two index, it is necessary to build composite index to improve data lookup and location.

 var animalschema = new Schema ({
  name:string,
  age:number,
  tags: {age: [String), index:true}/Field Level
 });

 Animalschema.index ({name:1, Age:-1}); Schema level

However, the establishment of this index may cause significant performance impact, it is recommended to stop under production, set the automatic index in set mode to False to prohibit

 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);
 });
 Alternatively, you can use the Create
 cat.create (function (err, Thor) {
  if (err) return Console.log (err);
  Console.log (Thor);
 });

R

Find
Animalmode.find (function (err, cat) {
 if (err) console.log (err);
 Console.log (cat);
})

FindOne
Animalmode.findone ({name: ' catname '}, function (Err, cat) {
 if (err) console.log (err);
 Console.log (cat);
})

FindByID
//is the same as FindOne, but it receives the _id of the document as an argument and returns a single document. _ID//Can be a string or ObjectId object.
Animalmode.findbyid (ID, function (err, adventure) {
 if (err) consoel.log (err);
 Console.log (Adventure);
});

When the Where
//query data type is a string, regular
animalmode.where (' Age ', ' 2 ') can be supported. EXEC (function (err, cat) {
 if (err) Console.log (err);
 Console.log (cat);
};

Animalmode
 . Where (' age '). GTE (1). LTE
 . Where (' name ', ' CatName ')
 . EXEC (function (err, cat) {
  if (err) console.log (err);
  Console.log (cat);
 };

U
update functions provided by official documents Model.update

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

    • Conditions Update Condition
    • Doc Update content
    • Option Update options
    • Safe (Boolean) security mode, default option, value is True
    • Whether a new document is created when the Upsert (Boolean) condition does not match, and the default value is False
    • multi (Boolean) whether to update multiple files, the default value is False
    • Strict (Boolean) strict mode, update only one piece of data
    • Overwrite (Boolean) overwrites data, default to False
    • Callback
    • Err returns value when error updates data
    • Numberaffected (I don't know for a moment)
    • Number of rows affected by Rawresponse
Animalmode.update ({name: ' CatName '}, {age: ' 6 '}, {multi:true}, function (err, numberaffected, raw) {
 if (err) return C Onsole.log (err);
 Console.log (' The number of updated documents was%d ', numberaffected);
 Console.log (' The raw response from Mongo is ', raw);

D

Animalmode.remove ({Age:6}, function (err) {
 if (err) console.log (err);
})

Other
Return number of documents

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

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.