【发布时间】: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” - 所以我认为这不适用,尽管我很好奇它为什么会显示。
【问题讨论】:
-
这包含你上一个问题的答案:github.com/Automattic/mongoose/issues/6880