Mogoose是设计用于异步环境的MogoDB对象模型工具,支持promises和callbacks。
概述连接到MogoDB首先需要定义一个连接。如果应用仅使用一个数据库,则使用mogoose.coect。如果需要创建其他连接,请使用mogoose.createCoectio。
coect 和 createCoectio都使用 mogodb://URI,或者 host,database,port,optios参数。
awaitmogoose.coect('mogodb://localhost/my_database');连接后,ope将在Coectio实例上触发该事件。
注意: 如果本地连接失败,请尝试使用127.0.0.1而不是localhost,更改本地主机名可能会出现问题。
Mogoose会缓冲所有命令,直到它连接到数据库,这意味着不必等到它连接到MogoDB才开始定义模型、运行查询。
定义模型模型是通过Schema接口定义的:
costSchema=mogoose.Schema;costObjectId=Schema.ObjectId;costBlogPost=ewSchema({author:ObjectId,title:Strig,body:Strig,date:Date});除了定义文档的结构和存储的数据类型之外,Schema还处理以下定义:
验证器(异步和同步)默认值GettersSetters索引中间件方法定义静态定义插件pseudo-JOINs以下是上述功能的一些用法:
costCommet=ewSchema({ame:{type:Strig,default:'hahaha'},age:{type:Number,mi:18,idex:true},bio:{type:Strig,match:/[a-z]/},date:{type:Date,default:Date.ow},buff:Buffer});//asetterCommet.path('ame').set(fuctio(v){returcapitalize(v);});//middlewareCommet.pre('save',fuctio(ext){otify(this.get('email'));ext();});查看examples/schema/schema.js示例中的典型设置端到端示例。
访问模型一旦我们通过 mogoose.model('ModelName',mySchema)定义了一个模型,就可以通过相同的函数访问它:
costMyModel=mogoose.model('ModelName');或者一次性完成:
costMyModel=mogoose.model('ModelName',mySchema);第一个参数是模型所针对的集合的单数名称。Mogoose会自动查找模型名称的复数形式。例如:
costMyModel=mogoose.model('Ticket',mySchema);Mogoose会为 tickets 集合建立模型,而不是 ticket集合。
一旦我们有了模型,就可以实例化并保存它:
costistace=ewMyModel();istace.my.key='hello';istace.save(fuctio(err){//});可以从同一个集合中找到文档
MyModel.fid({},fuctio(err,docs){//docs.forEach});









评论