我想确保数组中只有一个项目被标记为“当前”。所以我的想法是,如果传入的数据被标记为“current = true”,那么我想将所有其他项目更改为“current = false”。
数据如下所示:
{
_id:123,
name:"bob jones",
schools:[
{
name: "central HS",
current: false
},
{
name: "east side HS",
current: 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 is deprecated。请改用 findOneAndUpdate、findOneAndReplace 或 findOneAndDelete。
但我没有使用“findAndModify”——所以我认为这不适用,尽管我很好奇它为什么会显示。