Andre Coetzee
Andre Coetzee

Reputation: 1310

How to update a specific object in a array of objects in Node.js and Mongoose

I am new to node.js coming from java experience. I have a situation that I am trying to wrap my head around. My stack is express.js, mongoose, ejs template. Here is my scenario: I have a schema:

var UserSchema = mongoose.Schema({
name: {
    type: String,
    index: true
},
password: {
    type: String,
    select: false
},
email: {
    type: String
},
academic: [{
    qualification: String,
    institute: String,
    from: String,
    to: String,
    about: String
}]

});

there is a list of academics. I want to update only one academic object in that list. How would I go about this?

router.post('/academic/schools/update', function (req, res) {

});

I pass the values from ejs template into the route and getting the values in the req.body. How would I in node and mongoose query that specific object in the route and then updates its values. I have thought about maybe adding an Id to the academic object to be able to keep track of which to update.

Upvotes: 1

Views: 5316

Answers (1)

Henry Liu
Henry Liu

Reputation: 700

Each academic sub document will have an _id after you save. There are two ways you can do it. If you pass the id of the user and id of the academic sub-doc id in the url or request body, then you can update like this:

User.findById(userId).then(user => {
    let academic = user.academic.id(academicId);
    academic.qualification = 'something';
    return user.save();
});

If you only pass the id of the academic sub-doc, then you can do it like this:

User.findOne({'academic._id': academicId}).then(user => {
    let academic = user.academic.id(academicId);
    academic.qualification = 'something';
    return user.save();
});

Note that sub document array return from mongoose are mongoosearray instead of the native array data type. So you can manipulate them using .id .push .pop .remove method http://mongoosejs.com/docs/subdocs.html

Upvotes: 2

Related Questions