【问题标题】:How to update a field using its previous value in MongoDB/Mongoose [duplicate]如何使用 MongoDB/Mongoose 中的先前值更新字段 [重复]
【发布时间】:2017-10-25 10:31:41
【问题描述】:

我知道我可以使用 $set 进行更新:

Contact.update({
    _id: request.id
}, {
    $set: { name: newNameValue }
}, {
    upsert: false
}, function(err) { ... });

但在这种情况下,我不想传递newNameValue,而是使用之前的name 值来计算新的值。假设我想将旧名称大写,例如:

Contact.update({
    _id: request.id
}, {
    $set: { name: $old.name.toUpperCase() }
}, {
    upsert: false
}, function(err) { ... });

【问题讨论】:

  • 用一个语句很可能无法做到。

标签: mongodb mongoose


【解决方案1】:

我认为这里已经回答了这个问题:How to add new data to current string in MongoDB?,所以请检查它以获得更详细的答案,但无论如何,简而言之,你不能用一个查询来做到这一点。

使用Mongoose的方法,如this official Mongoose example所示:

Contact.findById(request.id, (err, contract) => {
    if (err) return handleError(err);

    contract.name = contract.name.toUpperCase();

    contract.save((err, contractContract) => {
        if (err) return handleError(err);

        ...
    });
});

【讨论】:

    【解决方案2】:

    据我所知这是不可能的。你需要找到然后更新

    Contact
        .find({
            _id: request.id
        })
        .exec(function(err, data) {
                if (err) {
                    return ...;
                }
                Contact.findByIdAndUpdate(request.id, {
                    $set: {
                        name: data.name.toUpperCase()
                    }
                }, {
                    new: true
                }, function(err, doc) {
                    if (err) return ...;
                    console.log(doc)
                });
            }
    

    【讨论】:

      猜你喜欢
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-14
      • 1970-01-01
      • 2019-12-15
      相关资源
      最近更新 更多