1

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.

Andre Coetzee
  • 1,260
  • 3
  • 20
  • 34
  • Mongoose should automatically add an _id field to each object in the academics array since it treats them as 'sub-documents'. You can query inside the academics array with { 'academics._id': _id } etc and then you can update the matched document by using the positional operator { $set: { 'academics.$' : yourUpdatedAcademic } } ... more info https://docs.mongodb.com/manual/reference/operator/update/positional/ – Carlos Sultana Jul 21 '16 at 15:58

1 Answers1

2

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

Henry Liu
  • 671
  • 1
  • 10
  • 19