Application of Mongoose to develop MongoDB (2) model (models)

Source: Internet
Author: User
Tags findone lowercase mixed table definition

Data model and Base operation template

In order to make the engineering structure clear, the establishment of data Model (SCHEMA) and the base operation template of adding and deleting and modifying are named as collection in database design (corresponding to the table definition in relational database) and stored in the Models folder.

Creation of schema and model:

Schema is the data schema in mongoose, which can be understood as the table structure definition; Each schema maps to a collection in MongoDB and does not have the ability to manipulate the database.

Consider the following code:

Introduce the Mongoose module var mongoose = require (' mongoose ');//define Schemavar Taskschema = new Mongoose in JSON object form. Schema ({         userid:string,         invalidflag:number,         task: [             {                _id:0,                type: {type:string},                details:[{                      starttime:date,                      frequencytimes:number,                      frequencyunits:string,                      status:number                } ]             }         ],          revisioninfo:{                   operationtime:date,                   userid:string         }});//Export Modelvar Taskmodel = Mongoose.model (' Task ', Taskschema);


This defines a schema and model that maps to a collection in MongoDB. In the actual operation process, the following points need to be noted:

1. Naming specification: First letter lowercase, if there are more than one word in the name, the first letter is lowercase, the other words are capitalized in the first letter. This is a list of the default conventions in this article, and different developers have different habits.

2. Define the schema as a JSON object as defined, the key is a property, the value is a property description, about the property description, at least need to define the type of the property (that is, type), if there are other needs to explain, the same as JSON, the key is the property, the value is a description.

3. Schema.types: There are 8 kinds of Schema Types available, including string, number, Date, Buffer, Boolean directly defined, Mixed, Objectid need to introduce mongoose module after definition Array is defined by using the brackets in the C $ type, which is not indicated or possible. The mixed type can be treated as a nested type, without specifying the key of the inner element, and if you need to specify the key of the inner element, you can use the curly Brace declaration (as above ' revisioninfo ') directly

Introducing the Mongoose Module
var mongoose = require (' mongoose ');//defined as JSON object Schemavar Taskschema = new Mongoose. Schema ({ _id:mongoose. Schema.Types.ObjectId,//Primary key doctor_id: {type:mongoose. Schema.Types.ObjectId, ref: ' Doctor '},//foreign key link to "Doctor" Content:mongoose. Schema.Types.Mixed//Mixed or nested type});


4. Other actions when defining the schema:

A) valid for all type:

Required:boolean or function. If the Boolean value is true, the model is validated.

Default: Sets the defaults for the property, which can be value or function.

This property is output by default when querying Select:boolean.

Validate:function, a custom validator for the property.

Get, set:function, value of custom property

Get, Set use example
Reference: Http:// Numberschema = new Schema ({ integeronly: { type:number, get:v = Math.Round (v), set:v = Math.Round (v) }); var number = Mongoose.model (' number ', Numberschema); var doc = new number ();d oc.integeronly = 2.001;doc.integeronly; 2


b) Index Indexes

Whether the Index:boolean property is indexed

Unique:boolean whether a unique index

Sparse:boolean Sparse Index: Sparse index, if the index key store value is NULL, skip this document, these documents will not be indexed to. However, instead of using sparse indexes by default at query time, you need to use hint () to specify the sparse indexes that are established in the model.

c) valid for strings string

Lowercase:boolean is converted to lowercase, which is called on a value. toLowerCase ()

Uppercase:boolean turns into uppercase, which is called on the value. toUpperCase ()

Trim:boolean removes the opening and closing spaces, which are called on values. Trim ()

Match: A regular expression that generates a validator to determine whether a value conforms to a given regular expression

Enum: An array that generates the validator to determine whether the value is in the given array

d) Valid for numeric number or time date

Min, max:number or date generation validator determines whether a given condition is met

5. Note:

When declaring a mixed type, the following methods are equivalent:

Introducing the Mongoose Module
var mongoose = require (' Mongoose '); Declare mixed type var any = new schema ({any: {}}), var any = new schema ({any:object}), var any = new schema ({any:mongoose. Schema.Types.Mixed});


About Arrays (array):

A) statement:

Introducing the Mongoose module var mongoose = require (' Mongoose '); An empty array with the declared type mixed var Empty1 = new schema ({any: []}), var Empty2 = new schema ({Any:array}), var Empty3 = new Schema ({any : [Mongoose. Schema.Types.Mixed]}); var Empty4 = new Schema ({any: [{}]});


b) Default properties:

The array implicitly contains the default value ("Default: []"), to remove this default value, you need to set the default value (default:undefined)

If the array is marked (required:true), the array must contain an element when the data is stored, otherwise it will be an error.

6. Custom Schema Type:

From Mongoose. SchemaType inherited, adding the corresponding attribute to mongoose. Schema.type, you can use the cast () function, for example, see:


7. Schema Options: A series of operations on the schema, because I have not verified, I will not elaborate.



In this file, in addition to exporting and compiling the data model, in addition to establish the database additions and deletions of the basic method, generate functions, export modules for other files to call.

Still in the above article: /models/task.js file as an example:

Set collection function with the same name and export the Module function task (Task) {         this.task = task;} Add basic addition and deletion check and change operation function template//...module.exports = Task;


Increase: = function (callback) {         var task = This.task;         var newtask = new Taskmodel (Task); (function (err, taskItem) {                   if (err) {                            return callback (ERR);                   }                   Callback (null, TaskItem);         });


It is important to note that the database document storage method is modified on the task prototype chain and is implemented using the Save () function. During the operation of the data store, first generate an instance from the prototype object, where the prototype object is the document to be stored. Complete the operation of generating an instance from a prototype object, using the new operator, while the new operator cannot share properties and methods, the Save () function is exactly the method that needs to be shared, so using prototype to set a function named Save () as a common method of documentation.

By deleting:

Unlike the Add method, the Delete, find, and modify methods directly add methods to the task, because these methods operate on the model, and the model's methods are defined within Node_modules/mongoose/lib/model.js.

Methods related to deletion:

Delete the first document matching conditions, to remove all, set ' justone ' = False

Remove (conditions, [callback]);

Delete the first document matching conditions, ignoring the justone operator

Deleteone (conditions, [callback]);

Delete all documents that match conditions, ignoring the justone operator

Deletemany (conditions, [callback]);

Implement the Findandmodify Remove command in MongoDB and pass the found document into the callback

Options: ' Sort ', ' maxtimems ', ' select '

Findoneandremove (conditions, [options], [callback]);

Delete the document with the primary key as the query criteria and pass the found document into the callback

Findbyidandremove (ID, [options], [callback]);

Task.removeone = function (query, callback, opts) {
var options = opts | | {}; Taskmodel . Findoneandremove (query, Options, function (err, Task) { if (err) { return callback (ERR); } Callback (null, Task); });


In this example, the exported function is named Task.removeone (), and when the parameter is passed in, the [option] is put to the end, and the intention is that the options are often empty and do not need to be passed in when actually applied. This can be omitted directly when writing the controller without the empty string placeholder. In fact, when defined in Model.js, it has been processed: conditions must be passed in, and cannot be a function, and when the second parameter options is function, the function is considered to be callback, and set the options to undefined

if (arguments.length = = = 1 && typeof conditions = = = ' function ') {
var msg = ' Model.findoneandremove (): First argument must not being a function.\n\n ' + ' + this.modelname + '. Findon Eandremove (conditions, callback) \ n ' + ' + this.modelname + '. Findoneandremove (conditions) \ n ' + ' + This.modelname + '. Findoneandremove () \ n '; throw new TypeError (msg); } if (typeof options = = = ' function ') { callback = options; options = undefined; }



Methods related to the modification:

Update documents without returning them

Option: ' Upsert ': If True if a document with no matching criteria is created

Option: ' Multi ': If True, update multiple documents

Option: ' Runvalidators ', if true, for model validation prior to update

Option: ' Setdefaultsoninsert ', if this operator and ' Upsert ' are true at the same time, the default value in the schema is new to the new document

Be careful not to use an existing instance as an UPDATE clause, which could lead to a dead loop

Note the _id field does not exist in the UPDATE clause because MONGODB does not allow this

When using update, the values are converted to the corresponding type, but defaults, setters, validators, middleware are not applied, and if you want to apply them, you should use FindOne () and then call the. Save () function in the callback function

Update (conditions, doc, [options], [callback]);

Ignore the multi operator to modify all conditions-compliant documents

Updatemany (conditions, doc, [options], [callback]);

Ignore the multi operator to modify only the first document that conforms to conditions

Updateone (conditions, doc, [options], [callback]);

Replace with new document instead of modify

Replaceone (conditions, doc, [options], [callback]);

Locate the matching document and update the document according to [UPDATE] and pass in the found document [callback]

Option: ' New ': If True, returns the updated document

' Upsert ', ' runvalidators ', ' setdefaultsoninsert ', ' sort ', ' select ' and other operators are also available

Findoneandupdate ([conditions], [UPDATE], [options], [callback]);

Find a matching document with the primary key and update the document with [UPDATE] to pass in the found document [callback]

Findbyidandupdate (ID, [UPDATE], [options], [callback]);

Task.updateone = function (query, obj, callback, opts, populate) {
var options = opts | | {}; var populate = Populate | | ‘‘; Taskmodel. Findoneandupdate (query, obj, options). Populate (populate) . exec (function (err, uptask) {if (err) {return callback (err ); } callback (null, uptask); });}; task.update = function (query, obj, callback, opts, populate) {var options = opts | | {}; var populate = Populate | | ‘‘; Taskmodel. Update (query, obj, options). Populate (populate). EXEC (fun Ction (Err, Uptask) {if (err) {return callback (ERR); } callback (null, uptask); });};


Unlike the Delete method, callback does not pass in. Update () or. Findoneandupdate (), and then a callback function is passed in after calling. EXEC (), and if Err has content, it returns ERR, otherwise it returns UPTASK. That is, the return of MongoDB. Such processing can not require the response of MongoDB to wait.

Populate is a parameter that is used when querying a table, which will be mentioned later in this section.


Query-related methods:

Conditions will automatically be transferred to the corresponding schematypes before the command is sent.

Find (conditions, [projection], [options], [callback]);

Query to a document via _id

FindByID (ID, [projection], [options], [callback]);

Queries a document that returns any document if condition = null or undefined

FindOne ([conditions], [projection], [options], [callback]);

Task.getone = function (query, callback, OPTs, fields, populate) {
var options = opts | | {}; var fields = Fields | | Null var populate = Populate | | ‘‘; Taskmodel. FindOne (Query, fields, opts). Populate (populate). EXEC (Fu Nction (Err, TaskInfo) {if (err) {return callback (ERR); } callback (null, taskinfo); });}; Task.getsome = function (query, callback, OPTs, fields, populate) {var options = opts | | {}; var fields = Fields | | Null var populate = Populate | | ‘‘; Taskmodel. Find (Query, fields, options). Populate (populate). EXEC (Fu Nction (err, tasks) {if (err) {return callback (ERR); } callback (null, tasks); });};


In the built-in parameters of the. GetOne () and. Getsome () functions, you can see that option, field, populate is behind callback, because the most basic case is that only query and callback are passed in, while the latter is less used. In some complex queries, these three are essential.

Although queries are the most complex, they are all combined with. Find () and. FindOne () with a variety of operators. Also because the most basic parameters are condition and callback, the two parameters are placed first when the function is exported. It is important to note that when the document is not queried,. FindOne () returns NULL,. Find () returns an empty array, which causes the necessary output validation to occur in some cases when the GetOne () function is called, or the error causes the program to crash.

Application of Mongoose to develop MongoDB (2) model (models)

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: 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.