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.

1
  • 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 docs.mongodb.com/manual/reference/operator/update/positional Commented Jul 21, 2016 at 15:58

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.