我想用Mongoose构建一对多的引用,但我不想保留一个id列表。
我有什么:
menuCategorySchema
var schema = new Schema({
menuItem: [{
type: Schema.ObjectId,
ref: 'menuItem'
}],
icon: String,
name: String
});
menuItemSchema
var schema = new Schema({
menuCategory: {
type: Schema.ObjectId,
ref: 'menuCategory'
},
name: String,
path: String
});
Mongo Collection menuItem:
{
"_id" : ObjectId("54be856e9ba3a972e4dc924e"),
"menuCategory" : ObjectId("54be84919ba3a972e4dc924d"),
"name" : "I am a menu item",
"path" : "/item/path"
}
Mongo Collection menuCategory:
{
"_id" : ObjectId("54be84919ba3a972e4dc924d"),
"icon" : "awsome",
"name" : "Main Category"
}
预期结果:
var menuCategory = require('./models/menuCategory');
menuCategory.find({}).populate('menuItem').exec(function(err,result){
console.log(result);
})
{
"_id": ObjectId("54be84919ba3a972e4dc924d"),
"icon": "awsome",
"name": "Main Category"
"menuItem": [{
"_id": ObjectId("54be856e9ba3a972e4dc924e"),
"menuCategory": ObjectId("54be84919ba3a972e4dc924d"),
"name": "I am a menu item",
"path": "/item/path"
}]
}
我能够用 menuCategory 填充 menuItem ,但我想反过来。