Home > Back-end >  How to update a specific nested array inside a MongoDB document
How to update a specific nested array inside a MongoDB document

Time:06-07

So I have a primary mongoDB object that has multiple documents nested within. I want to access a specific document in an array and modify one of its values. This is my document setup

const sectionSchema = new mongoose.Schema({
    name: String,
    items: [itemSchema],
    currentAmount: {
        type: mongoose.Decimal128,
        default: 0
    },
    limitAmount: {
        type: mongoose.Decimal128,
        required: true
    },
    isActive: {
        type: Boolean,
        default: 0
    }
});
const Section = new mongoose.model("Section", sectionSchema);

const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        unique:true
    },
    email: {
        type: String,
        lowercase: true,
        trim:true,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    sections: [sectionSchema]
});
    const User = new mongoose.model("User", userSchema);

I've added some dummy values to fill the database, including the other testSection and testItems.

const testSection2 = new Section({
    name: "Vacation",
    items: [testItem3,testItem4],
    currentAmount: 0,
    limitAmount: 800,
    isActive: 1
});

const testUser = new User({
    username: "wavey123",
    email: "[email protected]",
    password: "wvy123",
    sections: [testSection1,testSection2]
});

I've tried different iterations of the .findOneAndUpdate methods with no success like:

app.post("/sSelect", function(req,res){
    const selectedSection = req.body.sectionName;
    
    User.findOneAndUpdate({sections: {$elemMatch: {isActive: 1}}},{sections: {isActive: 0}},{new: true}, function(err, aSection){
        if (err){
            console.log(err)            
        }
        console.log(aSection);
    })
    
    User.findOneAndUpdate(({sections: {$elemMatch: {name: selectedSection}}}),{$set: {sections: {isActive: 1}}},{new: true}, function(err, aSection){
        if (aSection){
            res.redirect("/");
        }
    })

I end up with my base document looking like this:

[
  {
    _id: ObjectId("629a971bb8a72843a07df0fd"),
    username: 'wavey123',
    email: '[email protected]',
    password: 'wvy123',
    sections: [
      {
        currentAmount: Decimal128("0"),
        isActive: false,
        _id: ObjectId("629a9756792a3b21872c329f"),
        items: []
      }
    ],
    __v: 0
  }
]

This happens after the first .findOneAndUpdate. Cant seem to get my head around it.

CodePudding user response:

so i just scrapped the whole .findOneAndUpdate and just used JS to find the isActive key and manipulate it like so:

app.post("/sSelect", function(req,res){
    const selectedSection = req.body.sectionName;

    User.findOne({}, function(err, aSection){
        aSection.sections.forEach(function(section){
            if(section.isActive === true){
                section.isActive = false;
                console.log(section.isActive)
                aSection.save();
            }
        })
    });
    User.findOne({}, function(err, aSection){
        aSection.sections.forEach(function(section){
            if(section.name === selectedSection){
                section.isActive = true;
                console.log(section.name,section.isActive)
                aSection.save();
            }
        })
    });
    res.redirect("/");
  • Related