Vla*_*kic 5 mongoose mongodb node.js mongoose-populate
我有这样的查询:
galleryModel.find({_id: galleryId})
.populate({
model: 'User',
path: 'objectId',
select: 'firstName lastName'
})
Run Code Online (Sandbox Code Playgroud)
的最终响应objectId将如下所示:
objectId: {
...
}
Run Code Online (Sandbox Code Playgroud)
如何user在不更改实际路径的情况下将其更改为响应?
您可以通过在 mongoose 版本 4.5 中引入的虚拟填充来完成此操作。为此,您需要在 mongoose 模式中定义一个虚拟字段。
var GallerySchema = new mongoose.Schema({
name: String,
objectId: {
type: mongoose.Schema.Types.ObjectId
},
});
GallerySchema.virtual('user', {
ref: 'User',
localField: 'objectId',
foreignField: '_id'
});
Run Code Online (Sandbox Code Playgroud)
Ans 当您运行 find 查询时,只需用用户填充它。
Gallry.find({_id: galleryId}).populate('user','firstName lastName').exec(function(error, gallery) {
console.log(error);
console.log(gallery);;
});
Run Code Online (Sandbox Code Playgroud)
以上代码未在程序中测试,可能有错别字,您可以在下面的链接中获得有关猫鼬虚拟填充的更多详细信息
http://mongoosejs.com/docs/populate.html
| 归档时间: |
|
| 查看次数: |
1851 次 |
| 最近记录: |