【问题标题】:Mongoose adding new entry to parentMongoose 向父级添加新条目
【发布时间】:2015-06-01 15:53:24
【问题描述】:

我正在使用 express 和 mongoose 构建一个 REST API。我有以下架构:

var PostSchema= new Schema({
name: String,
_comments: [{ type: Schema.Types.ObjectId, ref: 'Comment'}]
});

var CommentSchema = new Schema({
text: String,
_post: { type: Schema.Types.ObjectId, ref: 'Post'}
});

我想在我的帖子中添加一条新评论:

/* POST a comment*/
router.post('/', function(req, res, next) {
var comment= new Comment(req.body);
comment.save(function (err, post) {
    if (err) {
        return next(err);
    }
    res.json(post);
});
});

它确实使用以下数据保存评论:

{text: "bla", _post: *postId*}

但是,当我使用填充的 cmets 检索我的帖子时:

/* GET post*/
router.get('/', function(req, res, next) {
Post.find().populate('_comments').exec(function (err, posts) {
    if (err) return next(err);
    res.json(posts);
});
});

cmets 数组为空。

所以我想当我在帖子中添加新评论时,我还需要将评论 id 添加到 post.cmets 数组并保存?有没有一种干净的方法可以做到这一点?

【问题讨论】:

    标签: node.js rest express mongoose


    【解决方案1】:

    保存comment(在回调中传递给comment.save)后,将其添加到post._comments$addToSet。这样做可以避免重复。

    Post.update({ _id: comment._post }, { $addToSet: { _comments: comment._id } }, {}).exec();
    

    【讨论】:

    • 谢谢,这正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 2018-08-28
    • 2012-12-10
    • 1970-01-01
    相关资源
    最近更新 更多