如何使用猫鼬填充?
How to use moongoose populate?
我有两个模式,一本书和另一个用户
let mongoose = require('mongoose'),
Schema = mongoose.Schema;
let book = new Schema({
id: {type : Schema.Types.ObjectId, default: null},
author: {type : Array, default: []},
userId:{type:Array,default:[]},
issued:[{type:Schema.Types.ObjectId,ref:'users'}]
});
let user = new Schema({
id: {type : Schema.Types.ObjectId, default: null},
name:{type : String, default: null},
address:{type : String, default: null}
});
Issued 属性 in book schema 包含发行书的用户的详细信息。
Issued Property can be populated by using userId of book Schema and
matching userId of book schema with an Id of user Schema.
let user = mongoose.model("Model", userSchema, "users");
let book = mongoose.model("book", bookSchema);
book.find({}).populate('users').exec(function (err, result) {
console.log(result);
//Query is failing what wrong i am doing.
});
我无法确定如何获取用户详细信息。
我想要这样的对象:
{
id: 8888998898989,
author: 'Author ',
userId:['232323232332','ssssssss'],
issued:[
{'id':232323232332,'name':'User1'},
{'id':ssssssss,'name':'User2'}
]
}
您需要使用带有对象字面量的填充方法,如下所示:
.populate({ path: 'id', model: 'ssers', select:'id name' })
您可以使用 lean() 查询,以便您可以修改输出,然后执行填充两个字段以仅保留您想要的字段:
.lean().populate('users', 'id name address')
可以找到更多示例here and here
.populate({ path: 'userId', model: 'users', select:'id name address' })
我有两个模式,一本书和另一个用户
let mongoose = require('mongoose'),
Schema = mongoose.Schema;
let book = new Schema({
id: {type : Schema.Types.ObjectId, default: null},
author: {type : Array, default: []},
userId:{type:Array,default:[]},
issued:[{type:Schema.Types.ObjectId,ref:'users'}]
});
let user = new Schema({
id: {type : Schema.Types.ObjectId, default: null},
name:{type : String, default: null},
address:{type : String, default: null}
});
Issued 属性 in book schema 包含发行书的用户的详细信息。
Issued Property can be populated by using userId of book Schema and matching userId of book schema with an Id of user Schema.
let user = mongoose.model("Model", userSchema, "users");
let book = mongoose.model("book", bookSchema);
book.find({}).populate('users').exec(function (err, result) {
console.log(result);
//Query is failing what wrong i am doing.
});
我无法确定如何获取用户详细信息。
我想要这样的对象:
{
id: 8888998898989,
author: 'Author ',
userId:['232323232332','ssssssss'],
issued:[
{'id':232323232332,'name':'User1'},
{'id':ssssssss,'name':'User2'}
]
}
您需要使用带有对象字面量的填充方法,如下所示:
.populate({ path: 'id', model: 'ssers', select:'id name' })
您可以使用 lean() 查询,以便您可以修改输出,然后执行填充两个字段以仅保留您想要的字段:
.lean().populate('users', 'id name address')
可以找到更多示例here and here
.populate({ path: 'userId', model: 'users', select:'id name address' })