I am using nodeJS with mongoldb 3.6.4. I have tried the Arrayfilter to update nested subdocument. But it is not updating the value. Here is the sample code I tried ( after incorporating the comments from Anthony Winzlet to make asyn Call)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var DrugRefSchema = new Schema({
drugRefs: [{
refName: String,
drugs: [{
name: String,
drugType:String,
}]
}]
});
module.exports = mongoose.model('DrugRef', DrugRefSchema);
async function UpdateMedList () {
const out = await DrugRef.aggregate([
{ $unwind: '$drugRefs'},
{ $unwind: '$drugRefs.drugs'},
{ $project : { refName:'$drugRefs.refName', med:'$drugRefs.drugs.name',_id:0}},
{ $group: {_id: { med: '$med',refName:'$refName'}}},
{ $project : { med:'$_id.med', refName:'$_id.refName',_id:0}},
])
out.map(async(data) => {
var refName=data.refName;
var oldName=data.med;
var newName=oldName.trim();
const updateName = await DrugRef.update(
{ },
{ $set:{"drugRefs.$[i].drugs.$[j].name":newName}},
{ arrayFilters: [ { "i.refName": refName },{ "j.name": oldName }], "multi": true }
)
console.log("Orig:'"+oldName+"': to be updated:'"+newName+"':");
console.log("update Result:"+JSON.stringify(updateName));
})
}
and name is not getting changed still. pl help
Issue was with mongoose version. It was 4.3. When I upgraded to 5.x it started working. Also when I upgraded with npm install mongoose with -g option it upgraded to 5.3.0 but my module mongoose was still pointing to 4.3. Then I had to install mongoose without -g also