【问题标题】:Mongoose update embedded documentMongoose 更新嵌入文档
【发布时间】:2023-03-10 15:12:01
【问题描述】:
id: { type: String, required: true, unique: true, default: uuid.v1 },
    description: { type: String },
    period: [{
        id: { type: String, default: uuid.v1 },
        start: { type: Date, default: Date.now },
        due: { type: Date },
        dueWarnByHours: { type: Number, integer: true },
        newnessByHours: { type: Number, integer: true },
    }],

我有一个像这样的嵌入式 mongodb 数据库文档。我尝试像下面这样更新它

WorkItem.update({ description: req.body.description},{period.rank: 3}, function(err, req) {
        if (err) return console.error(err);
        console.dir(reqWorkItemId + "Successfully removed the workItem from the database");
    });

但是如何更新嵌入的子部分期间不起作用->使用猫鼬排名

【问题讨论】:

  • description 是您查询中的唯一字段吗?如果您可以将句点数组作为查询文档的一部分,即WorkItem.update({ "description": req.body.description, "period.rank": { "$ne": 3 } },{ "$set": { "period.$.rank": 3 } }, callback);,则可以在更新中使用positional operator $

标签: node.js mongodb mongoose


【解决方案1】:
WorkItem.update({ id: d }, { description: req.body.description, $set: { 'status.0.rank': req.body.status.rank } },
        function(err, numRowsAffected, raw) {
            if (err) return console.error(err);
            if (numRowsAffected > 0) {
                console.dir("reqWorkItemId" + "Successfully removed the workItem from the database");
            } else {
                console.log("fail");
                //res.send(500, { error: 'carrier not updated' });
            }
        });

这个适合我

【讨论】:

    【解决方案2】:

    下面的代码会帮助你:-

    var findQuery = { description: req.body.description, 'period.id' : someId};
    WorkItem.update(findQuery,{$set:{'period.$.rank': 3}}, function(err, req) {
        if (err) return console.error(err);
        console.dir(reqWorkItemId + "Successfully removed the workItem from the database");
    });
    

     WorkItem.update(findQuery,{$set:{'period.$.rank': 3}}, function(err, req) {
        if (err) return console.error(err);
        console.dir(reqWorkItemId + "Successfully removed the workItem from the database");
    });
    

    注意:- 这只会更新周期数组的第一个对象。

    【讨论】:

    • 周期数组会有多个对象还是只有一个对象?
    • 查看对您的问题的评论,类似于您必须在查找查询中添加的内容,以使其正常工作。
    • 谢谢你我修好了。根据你的回答@Shrabanee
    猜你喜欢
    • 2014-06-12
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 2020-06-07
    • 2018-09-04
    • 2016-10-06
    • 2012-11-20
    相关资源
    最近更新 更多