【问题标题】:MongoDB setting a key in every object of an arrayMongoDB 在数组的每个对象中设置一个键
【发布时间】:2019-02-22 00:58:03
【问题描述】:

我想确保数组中只有一个项目被标记为“当前”。所以我的想法是,如果传入数据被标记为“current = true”,那么我想将所有其他项目更改为“current = false”。

数据如下所示:

{
    _id:123,
    name:"bob jones",
    schools:[
        {
          name: "central HS",
          current: false
        },
        {
           name: "east side HS",
           current: true
        }
    ]
}

因此,如果我要添加一所学校 - 我想确保现有学校被标记为当前:false - 仅当传入学校被标记为当前时:true。

传入的对象如下所示:

{
    name: "Discipline Military Academy HS",
    current: true
}

这是我尝试使用的代码。我没有收到错误消息 - 但是当前 = true 的现有学校仍然存在,没有变化。所以它似乎不起作用

注意:传入的 id 是人的 _id (_id:123)

module.exports.addSchool = function( id, data, callback ) {

    // reset all the other "currents" to false (only ONE current school permitted)
    if ( typeof data.current != 'undefined' && data.current === true ) {
        // NOTE:  a console.log('here'); shows I'm getting past the conditional... 
        User.update( {_id: id}, {$set: {'schools.0.current': false}} );
    }

    User.findByIdAndUpdate( id, { 
        $addToSet: {
            "schools": data
        }
    }, {new: true}, callback );

}

有什么建议吗?

注意:我正在使用 mongoose 5.2.13 将我的 express 应用程序连接到 mongoDB,我确实收到了这个警告 - (node:14508) DeprecationWarning: collection.findAndModify 已弃用。请改用 findOneAndUpdate、findOneAndReplace 或 findOneAndDelete。

但我没有使用“findAndModify” - 所以我认为这不适用,尽管我很好奇它为什么会显示。

【问题讨论】:

标签: mongodb mongodb-update


【解决方案1】:

用于将current : true 更新为current:false

请更改查询。

 db.getCollection('user').update( {
    "_id" : id,
    "schools.current": true }, 
    {$set: {'schools.$.current': false}});

【讨论】:

  • 这对我有用。我检查了 mongoDB 工具(robo3T)
  • 这应该确实有效。如果它没有更新您的记录,那么您传入的 _id 有问题。您可能希望从另一个客户端运行此查询和/或记录您的查询以查看 Mongoose 是否实际发送到 MongoDB:@ 987654325@.
猜你喜欢
  • 2020-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多