我需要更新一些字段 我正在使用 mongoose 驱动程序和 express js
架构:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ProfilesSchema = new Schema({
presentRound: {
type: Number,
default: 1
},
scheduleInterviewStatus: {
type: Boolean,
default: false
},
interviewStatus: String,
ratings: [{
round: Number,
rating: Number,
feedback: String,
interviewer: String,
roundStatus: String
}]
});
module.exports = mongoose.model('Profiles', ProfilesSchema);
所以在这些中我需要更新 id presentRound
scheduleInterviewStatus
interviewStatus
和 roundStatus(在 ratings 数组中匹配轮数)
更新前:
presentRound: 1,
scheduleInterviewStatus: true,
interviewStatus: "on-hold",
ratings: [{
round: 1,
rating: 3,
feedback: "good communication skills",
interviewer: "Vishal",
roundStatus: "second opinion"
}]
更新后:
presentRound: 2,
scheduleInterviewStatus: false,
interviewStatus: "in-process",
ratings: [{
round: 1,
rating: 3,
feedback: "good communicationskills",
interviewer: "Vishal",
roundStatus: "selected"
}]
我尝试先在 robomongo 中运行查询,但出现错误
Error: Fourth argument must be empty when specifying upsert and multi with an object.
查询:
db.getCollection('profiles').update({
"_id": ObjectId("57a9aa24e93864e02d91283c")
}, {
$set: {
"presentRound": 2,
"interviewStatus":"in process",
"scheduleInterviewStatus": false
}
},{
"ratings.$.round": 1
},{
$set: {
"ratings.roundStatus":"selected"
}
},
{ upsert: true },{multi:true})
我不知道我哪里错了
请帮忙。
最佳答案
你的 update
语句不正确,它的参数放错地方了——你放了多个 $set
操作和选项作为更新方法的不同参数;它们应该在单独指定的更新参数下。正确的 Node.js syntax是:
update(selector, document, options, callback)
其中 selector
是一个对象,它是更新操作的选择器/查询,document
也是一个对象,它是更新文档,最后是一个 options
默认情况下为 null 且具有可选更新设置的对象。
你在这做
update(selector, document, selector, document, options, options, callback)
其中 mongo 正在使用前两个参数正确更新集合,它自然会抛出错误
Error: Fourth argument must be empty when specifying upsert and multi with an object.
因为你指定了太多不正确的参数。
此外,您对位置运算符的使用不正确。它应该是要更新的文档的一部分,而不是在查询中。
为了正确实现,请遵循此更新
db.getCollection('profiles').update(
/* selector */
{
"_id": ObjectId("57a9aa24e93864e02d91283c"),
"ratings.round": 1
},
/* update document */
{
"$set": {
"presentRound": 2,
"interviewStatus": "in process",
"scheduleInterviewStatus": false,
"ratings.$.roundStatus": "selected"
}
},
/* optional settings */
{ upsert: true, multi: true }
)
关于node.js - 无法更新mongodb中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38864917/