【问题标题】:How to update this model that contains an array of objects in mongoose如何在猫鼬中更新包含对象数组的模型
【发布时间】:2017-08-18 02:03:54
【问题描述】:

我想知道如何使用 mongoose 更新喜欢的数组:

var postSchema = new mongoose.Schema({
    author: String,
    content: String,
    date: String,
    likes: [{theID: String}],
    numDate: Number
});

var UserSchema = mongoose.Schema({
    username: {
        type: String
    },
    password: {
        type: String
    },
    email: {
        type: String
    },
    first: {
        type: String
    },
    posts: [postSchema],
    last: {
        type: String
    },
    followers: [{theID: String}],
    following: [{theID: String}],
    img: { data: Buffer, contentType: String },
    admin: {type: Boolean, default: false}

});

我可以通过以下方式将新帖子等内容推送给数据库中的某个用户 这样做:

User.update({_id: req.user.id}, {
    $push: {"posts": {_id : req.body.theData}}
}, function(err, user){
    res.redirect('profile');
});

是否有类似的方法可以查看特定用户,然后查看用户拥有的特定帖子并更新它以将字符串推送到 likes 数组?

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    首先你需要选择你想要更新的不喜欢的帖子,你可以在帖子{_id: req.user.id,_id:posts._id}的_id的帮助下完成,然后你需要更新可以通过这种方式完成的数组@987654322 @ 如果用户不喜欢帖子以从数组中删除 id,您可以使用相同的方式提取用户 id。

    User.update({_id: req.user.id,_id:posts._id}, {
            $push: {"posts.$.likes": req.user.id}
        }, function(err, user){
    
        });
    

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 2019-02-20
      • 2020-07-31
      • 2016-03-09
      • 2012-03-20
      • 2021-04-03
      • 2019-09-14
      • 2015-01-13
      • 2022-08-18
      相关资源
      最近更新 更多