我有一个与 Angular 应用程序通信的 NodeJS 应用程序。这是一个简化版本,但我会尝试解释我的问题:
我将从套接字连接中获取一个值,例如:
{
Id : "1",
Checked : true,
TeamName : "Team1"
}
我想用 mongoose 更新 mongoDb,以便每个具有 TeamName :“Team1”的人都获得值 Checked :true。
我做了这样的事情:
relayModel.find({TeamName : 'Team1'},
{'$set' :{Checked: true}},function(err,docs){
if(err){
console.log("Could not save value for relay runner: ", err);
}
else{
console.log("The runners updated: ",docs)
}
但我收到错误:
Could not save value for relay runner:
{ [MongoError: Can't canonicalize query:
BadValue Unsupported projection option:
$set: { Checked: true }] name: 'MongoError' }
最佳答案
这确实有详细记录。肯定会消失,但只是为了向您解释一下:
relayModel.update(
{ "TeamName": "Team1" },
{ "$set": { "Checked": true } },
{ "multi": true },
function(err,numAffected) {
if (err) throw err;
console.log( "updated n docs: %s", numAffected );
}
);
因此,带有“multi”选项的 .update()
会影响多个文档,如果没有它,它只会影响第一个匹配的文档。回调中的返回值是标准的err
和“受影响的文档数量”。
因此基本上来说:
您实际上需要“更新”操作符才能影响和更新。
您为多个文档设置“multi”,并且您仅获得返回的数字以及使用
$set
运算符仅影响您要更改的字段。
关于javascript - 在 NodeJS 中使用 mongoose 设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25443883/