我有嵌套的数组文档结构,
{
"projectId": "12345-service-request",
"projectVersion": [{
"version":"1",
"localConfig": [{
"port": "3003",
"mongoURI": "mongodb://localhost:27017/serviceRequest",
"MQ": "RMQ",
"logLevel": "2",
"version": "1.1",
"created": "03-06-2018 03:11:00 PM",
"active": "Y"
},
{
"port": "3004",
"mongoURI": "mongodb://localhost:27017/serviceRequest",
"MQ": "IMQ",
"logLevel": "1",
"version": "1.2",
"created": "07-06-2018 03:11:00 PM",
"active": "Y"
}]
}]
}
现在,首先,我想将active
的所有localConfig
字段更新为N
,然后根据条件将特定的localConfig
active
设置为Y
。
为此,我编写了以下代码,
let updateActiveField = "projectVersion.$[]."+envQuery+".$[].active";
let conditions = { "projectId" : "32804-service-request-service" };
let update = { $set: { [updateActiveField] : "N" }};
let options = {};
ProjectConfig.update(conditions, update, options, function(err,result){
if (err) {
console.log(err);
}
console.log("## Finding new Pbject ##");
ProjectConfig.findOne({'projectId' : projectId,'projectVersion.version' : version}).exec(function(err,pc){
// console.log("## Update new document : "+JSON.stringify(pc));
if (err) {
console.log(err);
}
let projectVersionIndex = -1;
let projectVersionObject = {};
for(i = 0; i < pc.projectVersion.length ; i++){
if(pc.projectVersion[i].version === version){
if((pc.projectVersion[i][envQuery])){
projectVersionObject = _.filter(pc.projectVersion[i][envQuery], cloudParam);
projectVersionIndex = i;
}
}
}
console.log("## projectVersionIndex : "+projectVersionIndex);
console.log("## projectVersionObject : "+JSON.stringify(projectVersionObject));
let updateActiveField = "projectVersion.$[i]."+envQuery+".$[j].active";
let conditions = { "projectId" : "32804-service-request-service" };
let update = { $set: { [updateActiveField] : "Y" }};
let options = {arrayFilters:[{"i.version": [version] },{ "j.version" : [projectVersionObject[0].version]}]};
ProjectConfig.update(conditions, update, options, function(err,result){
if (err) {
console.log(err);
}
console.log("Document Updated");
});
});
})
在此代码中,第一次更新正常工作,但是第二次更新无法正常工作。 请提供正确的方法。
MongoDB的当前版本:v3.6.6
和Mongoose:^5.0.14
编辑:使用findOneAndUpdate
let updateActiveField = "projectVersion.$[i]."+envQuery+".$[j].active";
let conditions = { "projectId" : "32804-service-request-service" };
let update = { $set: { [updateActiveField] : "Y" }};
let options = {arrayFilters:[{"i.version": [version] },{ "j.version" : [projectVersionObject[0].version]}]};
ProjectConfig.findOneAndUpdate(conditions, update, options, function(err,result){
if (err) {
console.log(err);
}
console.log("Document Updated");
});
使用猫鼬调试true记录日志:
Mongoose: projectconfigs.findAndModify({ projectId: '32804-service-request-service' }, []
, { '$set': { 'projectVersion.$[i].localConfig.$[j].active': 'Y' } }, { arrayFilters: [ {
'i.version': [ '1' ] }, { 'j.version': [ '1.1' ] } ], new: false, upsert: false, fields:
{} })