创建后如何在猫鼬中填充子文档?

创建后如何在猫鼬中填充子文档?,第1张

创建后如何在猫鼬中填充子文档

为了填充引用的子文档,您需要显式定义ID所引用的文档集合(如

created_by: { type: Schema.Types.ObjectId, ref:'User' }
)。

假设已定义了此引用,并且在其他方​​面也对您的架构进行了很好的定义,那么您现在可以

populate
照常调用(例如
populate('comments.created_by')

概念证明代码:

// Schemavar mongoose = require('mongoose');var Schema = mongoose.Schema;var UserSchema = new Schema({  name: String});var CommentSchema = new Schema({  text: String,  created_by: { type: Schema.Types.ObjectId, ref: 'User' }});var ItemSchema = new Schema({   comments: [CommentSchema]});// Connect to DB and instantiate models    var db = mongoose.connect('enter your database here');var User = db.model('User', UserSchema);var Comment = db.model('Comment', CommentSchema);var Item = db.model('Item', ItemSchema);// Find and populateItem.find({}).populate('comments.created_by').exec(function(err, items) {    console.log(items[0].comments[0].created_by.name);});

最后请注意,该方法

populate
仅适用于查询,因此您需要先将项目传递到查询中,然后再调用它:

item.save(function(err, item) {    Item.findOne(item).populate('comments.created_by').exec(function (err, item) {        res.json({ status: 'success', message: "You have commented on this item", comment: item.comments.id(comment._id)        });    });});


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5121861.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-17
下一篇2022-11-17

发表评论

登录后才能评论

评论列表(0条)

    保存