ang*_*ord 21 mongoose mongodb node.js
是否可以使用不是_id的参考模型的字段填充mongoose模型...例如用户名.
所以像
var personSchema = Schema({
_id : Number,
name : String,
age : Number,
stories : { type: String, field: "username", ref: 'Story' }
});
Run Code Online (Sandbox Code Playgroud)
Fro*_*y Z 68
从Mongoose 4.5开始支持此功能,称为虚拟填充.
您必须在模式定义之后和创建模型之前定义外键关系,如下所示:
// Schema definitions
BookSchema = new mongoose.Schema({
...,
title: String,
authorId: Number,
...
},
// schema options: Don't forget this option
// if you declare foreign keys for this schema afterwards.
{
toObject: {virtuals:true},
// use if your results might be retrieved as JSON
// see http://stackoverflow.com/q/13133911/488666
//toJSON: {virtuals:true}
});
PersonSchema = new mongoose.Schema({id: Number, ...});
// Foreign keys definitions
BookSchema.virtual('author', {
ref: 'Person',
localField: 'authorId',
foreignField: 'id',
justOne: true // for many-to-1 relationships
});
// Models creation
var Book = mongoose.model('Book', BookSchema);
var Person = mongoose.model('Person', PersonSchema);
// Querying
Book.find({...})
// if you use select() be sure to include the foreign key field !
.select({.... authorId ....})
// use the 'virtual population' name
.populate('author')
.exec(function(err, books) {...})
Run Code Online (Sandbox Code Playgroud)
lee*_*sei -7
您可以使用populate()API。API更加灵活,你不必指定ref和field在Schema中
http://mongoosejs.com/docs/api.html#document_Document-populate http://mongoosejs.com/docs/api.html#model_Model.populate
您可以混合搭配find()。
| 归档时间: |
|
| 查看次数: |
19690 次 |
| 最近记录: |