Mongoose is an node.js
mongodb
object Model tool for convenient operation in the environment.
Therefore, to use mongoose
, you must install the node.js
environment and the mongodb
database. Mongoose makes MongoDB operations easier and easier. Can get its source code in GitHub, but also here to view the API documentation, English, the document content is more, so this article deliberately summed up mongoose
the schema
data model definition and simple delete and modify the API.
Connect
connect
Used to create a database connection
mongoose.connect(uri(s), [options], [callback])//url(s):数据库地址,可以是多个,以`,`隔开//options:可选,配置参数//callback:可选,回调mongoose.connect(‘mongodb://数据库地址(包括端口号)/数据库名称‘)
Specify user connections
mongoose.connect(‘mongodb://用户名:密码@127.0.0.1:27017/数据库名称‘)
Connect multiple databases
If you want to connect multiple databases in your app, you only need to set multiple URLs to ,
separate and set mongos
to True
mongoose.connect(‘urlA,urlB,...‘, { mongos : true })
Schema && model
Schema is a database model skeleton that is stored as a file, and does not have the ability to operate the database.
schema
Can be understood as a definition of the mongoose
table structure (not only can define the structure and properties of the document, but also can define the document's instance method, static model method, composite index, etc.), each schema
map to a collection in MongoDB, schema
do not have the ability to manipulate the database
Define Schema
GrammarNew Mongoose. Schema ({Fields ...}, [options])InstanceConst MONGOOSE = require (' mongoose ')const SCHEMA = Mongoose. SchemaConst OBJECTID = Schema.Types.ObjectIdConst ARTICLESCHEMA = New schema ({title: {type: String, requ Ired: True}, Contents: string, Author: string, Category: {Type:objectid, ref: ' category ' //Associated Cat Egory table _id}, Createtime: {type: Date, default: Date.now}}, {connection: ' article ', //model name,}) /c17>
Field type
The following field types are supported in the schema
String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array
Not only can you set the field type in the schema, but you can also set the default value, the associated document (ref), required, and so on. _ Once the field type is set, if an error occurs, such as if a field type is Boolean
, and a different type is entered, mongoose will throw a hint of type error _
Options
//常用到的`collection`,其他请参考[文档](http://www.nodeclass.com/api/mongoose.html#index_Mongoose-Schema){ _id : true, //Boolean, 唯一索引, 如果不需要,可以设置为false关闭 collection : ‘文档名称‘, //在MongDB中默认使用Model的名字作为集合的名字,如过需要自定义集合的名字,可以通过设置这个选项 versionKey : ‘__v‘, //包含文档的内部修订,默认的是__v autoIndex, capped : Number, //上限设置,此属性对批量操作有效,用来限制一次对数据库操作的量 id, //mongoose分配给每一个schema一个虚拟属性id,它是一个getter。返回的是_id转换为字符串后的值 read, safe, shardKey, strict, toJSON, toObject}
Model
The model is a schema-compiled hypothetical (fancy) constructor with abstract properties and behavior. Each instance of model (instance) is a document. Document can be saved to the database and manipulated against the database.
//语法mongoose.model(`文档名称`, Schema)//实例module.exports = mongoose.model(`Article`, ArticleSchema )
Methods instance method
Model
is an instance of document
. Built-in instance methods such as save
, you can methods
customize extension methods to instances by attributes
function() { // body...}
Statics static method
There are many static methods for model, such as, find
update
etc., which can be statics
added by attributes to Model
custom extension methods
function() { // body...}
The difference between Methods and Statics
statics
is to add a method model
, which methods
is to add a method to an instance (instance). The difference between methods and statics
//接上面代码,//module.exports = mongoose.model(`Article`, ArticleSchema )//将article的model保存为文件 article.jsconst Article = require(‘../models/article‘)// staticsArticle.staticFunc ()//methodsconst article = new Article(arguments)article.methodFunc()
Find
find
Used to query multiple documents
Model.find(conditions, [fields], [options], [callback])conditions <Object> //查询条件[fields] <Object> //要查询的字段[options] <Object> //查询配置参数[callback] <Function> //回调
Conditional query
Common Properties in conditional queries
$or or relationship
$nor or relationship Inversion
$GT Greater than
$gte greater than or equal to
$lt less than
$lte less than or equal to
$ne Not equal to
$in within multiple value ranges
$nin not within multiple value ranges
$all match multiple values in an array
$regex Regular, for fuzzy queries
$size Match Array size
$maxDistance range Query, distance (lbs-based)
$mod modulo operations
$near neighborhood query, find nearby locations (based on lbs)
Whether the $exists field exists
$elemMatch match elements within an array
$within range Query (based on lbs)
$box range query, rectangular range (based on lbs)
$center range, circular range (lbs based)
$centerSphere range Query, spherical range (lbs based)
$slice query the elements in the field collection (for example, from the first, nth to the first m elements
To query for articles with a reading volume greater than 500 less than 600
Article.find({views : {$gte : 500 , $lte : 600}})
Options
See this document
FindByID
findById
Used to id
query a single document
Model.findById(id, [fields], [options], [callback])
FindOne
findOne
Used to query a single document by condition
Model.findOne(conditions, [fields], [options], [callback])
Populate
populate
Used to view the associated document contents, that is, the ref
related fields of the document associated with the query set field
Model.populate (Docs, Options, [CB (ERR,DOC)])Exampleyield article.findone ({_id:id}, {title: 1, Author: 1}). Populate (1, _id: 1}}) //find _id as ID for the category field of the article corresponding to the classification name in the category table and Id// Multiple associated tables need to use array yield article.findone ({_id:id}, {title: 1, Author: 1}). populate ([{path: ' comments ', 1, User: 1, Text: 1,},}, {path: //the category field of the article, select : {fields ...}])
Paging and sorting
yield Article.findOne({ _id: id}, { title: 1, author: 1}, { sort: { createTime: -1, //倒序 desc _id: -1 }, skip: (page - 1) * pageSize, //page : 当前页码, pageSize 每页显示条数 limit: pageSize})// sort : -1 => desc , a => asc
Fuzzy query
Please see the blog "Implementation of MONGOOSE Multi-conditional fuzzy query"
Count
count
method is used to count the total number of document collections that match the criteria
Model.count(conditions, [callback])
Update
Model.update(conditions, update, [options], [callback])//查找并更新Model.findByIdAndUpdate(id, [update], [options], [callback])Model.findOneAndUpdate([conditions], [update], [options], [callback])
Update modifier
1}})//找到id=_id记录,并且将 views递增,返回后的views为之前的views+1。ps:这个属性很有用,对数字直接进行增减。用于更新一些数字(如阅读数)很有用`$set` 指定字段的值,这个字段不存在就创建它。可以是任何MondoDB支持的类型。Article.update({_id : id}, {$set : {views : 51, title : ‘修改后的标题‘ ...}})//更新后views为51,标题为‘修改后的标题‘`$unset` 同上取反,删除一个字段Article.update({views : 50}, {$unset : {views : ‘remove‘}}) //执行后: views字段不存在
Optional parameter, third parameter
{ new: true, //为true:返回update后的文档,false:返回update前的,默认是false sort: null, //排序条件,与sort函数的参数一致。 fields: null, //要返回的字段, 与find*的第二个参数一致。 upsert: null, // 如果是true,表示如果没有符合查询选择器的文档,mongo将会综合第一第二个参数向集合插入一个新的文档 multi: false, //true:更新匹配到的所有文档,false:更新匹配到的第一个文档}
Save
save
is an instance method that needs to be used new Model()
to get the instance first
const article = new Article({ //字段 => value //...})yield article.save()
Remove
Model.remove(conditions, [callback])//查找并删除Model.findByIdAndRemove(id, [options], [callback])Model.findOneAndRemove(conditions, [options], [callback])
Summary
The above is only the simplest use summary of the mongoose document, such as the where
method or the operation of the array is not included in the specific official document mainly
Mongoose Brief API