Mongoose Document (i) schemas

Source: Internet
Author: User
Tags mongodb collection

1. Define Shcema

In Mongoose everything starts with the schema. Each schema corresponds to a MongoDB collection and defines the model of documents in that collection.

var mongoose = require (' Mongoose '); var Schema = Mongoose. Schema; var New Schema ({  title:  string,  author:string,  body:   string,  comments: [{body:string, Date:date}],  default: Date.now},  Hidden:boolean,  meta: {    votes:number,< C19/>favs:  number  }});

After that, if you want to add extra keys, use the schema#add method

Each key in Blogschema defines a property in document that will be converted to its associated schema type. For example, the title that we have defined is converted to the string schema type and date is converted to the date Schema type. The key can also be specified as a nested object that contains more Key/type definitions (for example, the ' meta ' attribute above).

The legal schema type is

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

See more

Shema not only defines the structure and properties of the document, but also defines the document instance method, the static model method, the composite index, and the document life cycle hook called middleware.

2. Create a model

Using schema definitions, you need to convert the Blogschema to a working model. To do this, we pass it on to

Mongoose.model (modelname, schema)

var Blog = mongoose.model (' blog ', Blogschema); // Ready to go!

3. Example method

The example of model is document. Document has many built-in instance methods. We can also define our own method of document instance.

// Define a schema var New Schema ({name:string, type:string}); // assign a function to the ' methods ' object of our Animalschema function (CB) {  returnThis this. Type}, CB);}

Now all of our animal instances have the Findsiilartypes method available.

var Animal = Mongoose.model (' Animal ', Animalschema); var New Animal ({type: ' dog ' });d og.findsimilartypes (function  (err, dogs) {  //  Woof});

The re-default Mongoose document method can result in unpredictable results.

4. Static

Adding a static method to the model is straightforward. Continue to Animalschema.

// assign a function to the ' statics ' object of our Animalschema function (name, CB) {  returnthisnew RegExp (name, ' I ')}, CB);} var Animal = Mongoose.model (' Animal ', Animalschema); Animal.findbyname (function  (err, animals) {  console.log (animals);});

5. Index

MongoDB supports level two indexes. In Mongoose, the index of the schema is defined at the either the path level or the schema hierarchy. When you create a composite index, it is necessary to define the index in Shema.

var New Schema ({  name:string,  type:string,  true//  field  level // schema level

When the program starts, Mongoose automatically calls Ensureindex for each index defined in the schema. Mongoose will call Ensureindex for each index consecutively, when all Ensureindex calls succeed or an error occurs in the model issue of the index event. It is recommended that this behavior is prohibited in production because index creation can cause significant performance impact. Disable the behavior by setting the AutoIndex option to schema false or the connection global setting option to false config.autoindex.

false ); // or New false });

Model#ensureindexes method

6, Virtuals

Virtual is the document property that you can get and set but cannot save to MongoDB. Getter is used for formatting or conforming field, while setter is used to de-composing a single value to multi-value storage.

// Define a schema var New Schema ({  name: {    first:string,    last:string  }}); // Compile our model var person = Mongoose.model (' person ', personschema); // Create a document var New Person ({    ' Walter ', Last: ' White ' }});

Let's say we want to record bad's full name, we do this:

// Walter White

Or we can define a virtual property getter in Personschema, so we don't have to write these string connections every time

Personschema.virtual (' Name.full '). Get (function  () {  returnthis this  . Name.last;});

Now, when we use the virtual attribute, the Name.full,getter function is executed and the return value

// Walter White is insane

Primarily if the result record is converted to object or JSON, virtual is not included by default.

It is pleasing to set This.name.first and this.name.last by setting This.name.full. For example, we want to change the Name.first and name.last of bad respectively to ' breaking ' and ' bad ', which can be:

Bad.name.full = ' Breaking Bad ';

Mongoose also let you do this through its virtual property setters.

Personschema.virtual (' Name.full '). Set (function  (name) {  var split = Name.split (') );   this. Name.first = Split[0];   this. name.last = split[1= ' Breaking Bad '//  breakingconsole.log (mad.name.last);  //  Bad

The virtual property setter is applied before other validations. So the above example can still work. Even if you need Name.first and Name.last fields.

As part of the query and for field selection, only non-virtual properties are valid.

7. Option
New Schema ({..}, options); // or var New Schema ({..}); Schema.set (option, value);

Valid options

    • AutoIndex
    • Capped
    • Collection
    • Emitindexerrors
    • Id
    • _id
    • Minimize
    • Read
    • Safe
    • Shardkey
    • Strict
    • ToJSON
    • Toobject
    • Typekey
    • Validatebeforesave
    • Versionkey
    • Skipversioning
    • Timestamps

Mongoose Document (i) schemas

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.