【问题标题】:Mongoose findOneAndUpdate - update one field using another [duplicate]Mongoose findOneAndUpdate - 使用另一个字段更新一个字段[重复]
【发布时间】:2018-04-19 19:41:43
【问题描述】:

考虑这个架构:

var UserSchema = new Schema({
    ...
    user_id: {type:String},
    previous_selection: {type:String},
    current_selection: {type:String}
});

我需要编写一个函数,它将previous_selection 的值更新为给定user_idcurrent_selection 值。

findOneAndUpdate 有什么办法吗?

有点像 -

MyModel.findOneAndUpdate(
        { user_id: id }, 
        { $set: {"previous_selection": current_selection }},
        {}, 
        callback
);

或者有没有更好的方法来实现这一点?我是否必须做一个find() 然后更新?

【问题讨论】:

  • 你不能在单个更新中用另一个字段更新一个字段,你必须调用一个 find 方法来完成这个

标签: node.js mongodb mongoose


【解决方案1】:

根据您的关注,您可以这样做来更新整个集合。

db.MyModel.find({}).snapshot().forEach(
function (elem) {
    db.MyModel.update(
        {
            _id: elem._id
        },
        {
            $set: {
                "previous_selection": elem.current_selection
            }
        }
    );
});

否则,您可以通过 id 找到并使用相应的 current_selection 进行更新。

【讨论】:

  • .snapshot() 有什么作用?
  • 它只是防止多次返回文档。
  • 不错;但多次返回同一个文档,还是重复?
猜你喜欢
  • 2016-09-13
  • 2019-09-27
  • 1970-01-01
  • 1970-01-01
  • 2020-11-19
  • 2011-02-06
  • 1970-01-01
  • 2020-12-29
  • 1970-01-01
相关资源
最近更新 更多