Mongoose Reference Manual
tags (space delimited): MongoDB
In general, we do not directly use MongoDB functions to manipulate MongoDB database Mongose is a set of Operations MongoDB database interface.
Schema
A database model skeleton, stored as a file, does not have direct access to the database, which means that it does not have the ability to manipulate the database. Can be said to be a data attribute model (the traditional meaning of the table structure), or a "set" model skeleton
/* Define a Schema */VarMongoose= Require("Mongoose");Var Testschema = NewMongoose.Schema({Name: {Type:String },Property name, type stringAge: {Type:Number, default:0 }, //attribute age, type number, default = 0 time : { Type:date, default:date. Now }, Email: { Type:string,default: "}});
The above Testschema contains 4 attributes [name, age, time, email]
Model
The model generated by schema constructs, in addition to the database skeleton defined by the schema, has the behavior of database operations, similar to the classes that manage database properties, behaviors
var db = mongoose.connect("mongodb://127.0.0.1:27017/test");// 创建Modelvar TestModel = db.model("test1", TestSchema);
The collection name in the Test1 database does not exist and is created.
Entity
Entities created by model, save data using the Save method, model and entity have operations that can affect the database, but model is more operational than entity
Var Testentity = New Testmodel({Name: "Lenka", Age : $ , email: "[email protected]"}); Console. Log(testentity. Name); //Lenkaconsole. Log(testentity. Age); //
Cursor
MongoDB uses cursors to return the execution results of find. The client-side implementation of the cursor usually provides effective control over the final result. You can limit the number of results, skip the partial results, sort the results by any combination of the keys in any order, or perform some other strong action.
ObjectId
Each document stored in the MongoDB collection has a default primary key _id, which is fixed and can be any data type supported by MongoDB, which is objectid by default.
Objectid is a 12-byte BSON type string. In byte order, for: 4 bytes: Unix Timestamp 3 bytes: Represents the machine running MongoDB 2 bytes: Represents the process that generated this _id 3 bytes: The value generated by a counter that starts with a random number
In node. js
Package.json Add "Mongoose": "*" Field NPM install dependency.
var mongoose = require("mongoose");var db = mongoose.connect("mongodb://localhost:27017/test");
Then reference
Api
var mongoose = require("mongoose");var db = mongoose.connect("mongodb://localhost:27017/test");
DB-Database operations
1. Hook up the database connection event, parameter 1: It can also be error.
Db.connection.on (' Open ', callback);
Schema-Table structure
1. Constructors
New Mongoose. Schema ({name:{type:string}, Age:{type:number, default:10}})
2. Adding attributes
Schema.add ({name: ' string ', email: ' String ', Age: ' Number '})
3. Sometimes schemas not only provide public properties for the latter model and entity, but also provide a common approach
Schema.method (' Say ', function () {console.log (' Hello ')})//This method can be used by example of model and entity
4. Add a static method
Schema.static (' Say ', function () {console.log (' hello ');})//static method, only available at the model level
5. Append method
Schema.methods.say = function () {console.log (' hello ');}; Static methods, which can be used only at the model level
Model-Document operations
1. Constructor, Parameter 1: Collection name, parameter 2:schema instance
Db.model ("Test1", Testschema);
2. Query, parameter 1 is ignored, or empty object returns all collection documents
Model.find ({}, callback);
Model.find ({},field,callback); Filter query, Parameter 2: {' name ': 1, ' Age ': 0} The returned result of the query document contains the name, which does not contain age. (_id default is 1)
Model.find ({},null,{limit:20}); Filter query, Parameter 3: Cursor operation limit limits the number of returned results is 20, if less than 20 returns all.
Model.findone ({}, callback); The first document found by a query
Model.findbyid (' obj._id ', callback); Query the first document found, ibid. But only accept the value of __id query
3. Create, create a document in the collection
Model.create (document data, callback))
4. Update, Parameter 1: Query condition, Parameter 2: Update object, you can use Mondodb's update modifier
Model.update (conditions, UPDATE, function (Error)
5. Delete, Parameter 1: query criteria
Model.remove (Conditions,callback);
Entity-Document operations
1. Constructors are actually examples of model
New Testmodel ({name: ' Xueyou ', age:21});
2. Create, create a document in the collection.
Entity.save (callback);
Modifier and Updater Update modifiers:
' $inc ' increases or decreases the modifier, only valid for the number. The following example: Find age=22 documents, modify the document's age value from 1
Model.update ({' Age ': $}, {' $inc ': {' age ': 1}}); After execution: age=23
' $set ' Specifies the value of a key that does not exist to create it. can be any type supported by Mondodb.
Model.update ({' Age ': $}, {' $set ': {' age ': ' Haha '}}); After execution: age= ' haha '
' $unset ' to reverse, delete a key
Model.update ({' Age ': $}, {' $unset ': {' age ': ' Haha '}}); After execution: Age key does not exist
Array Modifiers:
' $push ' gives a key to push an array member, the key does not exist will create
Model.update ({' Age ': $}, {' $push ': {' array ': 10}}); After execution: Add an array key, type an array, have a member 10
' $addToSet ' adds an element to the array and does not add if it exists
Model.update ({' Age ': $}, {' $addToSet ': {' array ': 10}}); After execution: There are 10 in the array so it is not added
' $each ' iterates through arrays, and $push modifier mates can insert multiple values
Model.update ({' Age ': $}, {' $push ': {' array ': {' $each ': [1,2,3,4,5]}}}); After execution: array: [10,1,2,3,4,5]
' $pop ' removes an element from the tail of the array
Model.update ({' Age ': $}, {' $pop ': {' array ': 1}}); After execution: array: [10,1,2,3,4] Tips: Change 1 to 1 to delete array header elements
' $pull ' removes the specified element from the array
Model.update ({' Age ': $}, {' $pull ': {' array ': 10}}); After execution: array: [1,2,3,4] matches to 10 in array and deletes it
Conditional query:
- "$lt" is less than
- "$lte" is less than or equal to
- "$GT" is greater than
- "$gte" is greater than or equal to
- "$ne" is not equal to
Model.find ({"Age": {"$get": "$lte": 30}}); Querying for documents with age greater than or equal to 18 and less than or equal to 30
or query or:
- ' $in ' a key that corresponds to multiple values
- ' $nin ' to reverse, a key does not correspond to the specified value
- "$or" multiple criteria matching, can be nested $in use
- "$not" inverse, querying for documents that do not match a specific pattern
Model.find ({"Age": {"$in": [20,21,22. ') Haha ']}); Querying for documents with age equal to 20 or 21 or 21 or ' haha '
Model.find ({"$or": [{' Age ': +}, {' name ': ' Xueyou '}]}); Query for a document where age equals 18 or name equals ' xueyou '
Type query:
Null can match itself and non-existent value, want to match the value of the key is null, the "$exists" condition to determine the key value already exists "$exists" (indicates whether the meaning of existence)
Model.find ("Age": {"$in": [null], "exists": true}); Querying for documents with an age value of NULL
Model.Find({Name: {$exists: True}},function (error,docs< Span class= "pun") { //query all documents that exist the name attribute model.telephone: {< Span class= "PLN" > $exists : false}},function (error,docs //query all documents that do not have telephone properties });
Regular Expressions:
MongoDb uses Prel-compatible regular expression libraries to match regular expressions
Find ({"name":/joe/i}) queries the document named Joe, ignoring the case
Find ({"name":/joe?/i}) query matches various case combinations
Query array:
Model.find ({"Array": 10}); Query Array (array type) key has 10 of the document, array: [1,2,3,4,5,10] will match to
Model.find ({"array[5]": 10}); Query Array (array type) key subscript 5 corresponds to a value of ten, array: [1,2,3,4,5,10] will match to
' $all ' matches multiple elements in an array
Model.find ({"Array": [5,10]}); The query matches both 5 and 10 of the documents in array arrays
' $size ' matches array length
Model.find ({"array": {"$size": 3}}); The query matches a document with an array length of 3
' $slice ' query sub-collection returns
Model.find ({"array": {"$slice": 10}}); The query matches the first 10 elements of array arrays
Model.find ({"array": {"$skice": [5,10]}}); The query matches the 5th to 10th elements of an array of arrays
where
Use it to execute any javacript statement as part of the query, and if the callback function returns True the document is returned as part of the result
Find( {"$where" : function(){For( VarXInch This ){ The This in this function is the document}If(This.X!== Null && This.Y!== Null){ Return this. X + this.=== 10 ? true : false }else{ true;}} } Span class= "pun")
Simplified version
find( {"$where" : "this.x + this.y === 10" } )find( {"$where" : " function(){ return this.x + this.y ===10; } " } )
Cursor:
- Limit (3) limits the number of returned results,
- Skip (3) skips the first 3 documents and returns the remaining
- Sort ({"username": 1, "Age":-1}) sort key corresponding to the key name of the document, the value represents the sort direction, 1 ascending, 1 descending
https://cnodejs.org/topic/548e54d157fd3ae46b233502
What is Mongoose?