Mongoose Simple Learning Notes

Source: Internet
Author: User

1.1 Noun explanations
    • Schema: A database model skeleton stored as a file, not capable of database operation

    • Model: The Schema model generated by the publication, database operations with abstract properties and behaviors

    • Entity: by Model Creating an entity, his actions also affect the database

Attention:

1. This learning document uses a strict naming method to differentiate different objects, such as:

    var PersonSchema;   //Person的文本属性    var PersonModel;    //Person的数据库模型    var PersonEntity;   //Person实体

2.,, and Schema Model Entity the relationship please keep in mind that Schema generation Model , Model creation Entity , Model and Entity both can affect database operations, Model but Entity more operational.

Catalogue [-]

    • Installing Mongoose
    • Connecting to a database
    • Define your Schema
    • Database operations
Installing Mongoose
install mongoose
Connecting to a database
var mongoose = require(‘mongoose‘);mongoose.connect(‘mongodb://localhost/test‘);
Define your Schema

The schema here is the equivalent of a model, but there is also an idea of model in mongoose in addition to Schma. It is possible to understand this temporarily: we first define the schema and then generate the model from the schema, at which point the model has a way of interacting with the database.

Let's start by defining a blog post schema, as follows.

var blogSchema = new Schema({  title:  String,  author: String,  body:   String, comments: [{ body: String, date: Date }], date: { type: Date, default: Date.now }, hidden: Boolean, meta: { votes: Number, favs: Number }});

In the object structure of the schema constructor that we pass to Mongoose, key represents the property name that we define, and value is the type of this property. Several types of mongoose are currently allowed:

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

Among these types, other than mixed, Objectid are schema.types properties, others are JavaScript-owned.

After the schema is defined, we generate the model from it.

var Blog = mongoose.model(‘Blog‘, blogSchema);

Then, when we need to initialize a log of a blog post, we can initialize it like this:

var blog = new Blog({    is my blog title‘,    author: ‘me‘,    body: ‘the body of my blog. can you see that?‘ });
Database operations

After defining the model, we can make a record of the additions and deletions to check the changes. Mongoose to add and delete is very simple, with our previous section of the blog model for example, when we initialized a blog post record, and did not save it into the database. At this point, we can simply invoke the Save method of the blog instance to insert the record into the database.

blog.save();

You can also pass an error callback function to the Save method, which will be called if an error occurs during the save process.

Another way to save records is to use our previously defined blog object to invoke its Create method:

Blog.create({     ‘another blog title‘,     author: ‘still me‘,     body: ‘the blog body again!‘ }, function (err, small) { if (err) return handleError(err); // saved!});

There is a record in the database, and the next step may be to make a query. For example, an article that queries the author "Me". One way is to:

Blog.find({ author: ‘me‘ }).exec(callback);

Another approach is to:

Blog.find({ author: ‘me‘}, callback);

Basically all the model methods involved in the query have two forms of query, one is not to pass the callback function to the query method, when the query method does not execute the query immediately, but instead returns a query object, the user can then modify the Queries object on the search condition until exec ( Callback) method, and the second is to pass the callback function to the query method, when the query method executes immediately.

The former is recommended because it is convenient to specify complex conditions and to use for chained calls. For example I can find such a blog post:

Blog.find({ author: ‘me‘ }).where(‘title‘).equals(‘this is title‘).where(‘meta.votes‘).gt(17).lt(66).limit(10).sort(‘-date‘).select(‘title author body‘).exec(callback);

Now that we've inserted the data and we can query it, we're going to delete some of the records we don't need. The code is also relatively simple:

‘me‘ }, function (err) {  if (err) return handleError(err); // removed!});

The last is the update. In Mongoose, the Update method of the model is only updated and does not return objects. If you need to get the object you want to update, use the Findoneandupdate method of the model.

‘me‘ }, { title: ‘new title‘ }, { multi: true }, function (err, numberAffected, raw) { if (err) return handleError(err); console.log(‘The number of updated documents was %d‘, numberAffected); console.log(‘The raw response from Mongo was ‘, raw);});

At this point, mongoose simple additions and deletions are considered to be an empty, and then write a detailed content.

Mongoose Simple Learning Notes

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.