mongoose update subdocument array object code example

Example 1: mongoose update subdocument by id

//this method for add data to subdocument
BlogPost.findById(req.params.postId, function (err, post) {
    var subDoc = post.comments.id(req.params.commentId);
    subDoc = req.body;
    post.save(function (err) {
        if (err) return res.status(500).send(err);
        res.send(post);
    });
});

// alternative second method you can use this
BlogPost.findOneAndUpdate({_id: req.params.postId}, {$push:{ subDoc: req.body }}, (err, doc) => {
  	// do something here
});

Example 2: mongoose update subdocument by id

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const saltRounds = 10;
const Role = require('../config/roles')
const subscription = require('./subscriptionModel')

const Schema = mongoose.Schema;

const userModel = new Schema({
    created: { type: Date, default: Date.now },
    updated: { type: Date, default: Date.now},
    fullname: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    birthDate: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    profileImage: {
        type: String
    },
    role: {
        type: String,
        default: Role.user
    },
    subscriptions: [subscription.modelName]
})

// hash user password before saving into database
userModel.pre('save', async function save(next) {
    if (!this.isModified('password')) return next();
    try {
      const salt = await bcrypt.genSalt(saltRounds);
      this.password = await bcrypt.hash(this.password, salt);
      return next();
    } catch (err) {
      return next(err);
    }
});
  
// Compare passwords when user tries to log in.
userModel.methods.comparePassword = function(candidatePassword, cb) {
    bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
        if (err) return cb(err);
        cb(null, isMatch);
    });
};

module.exports = mongoose.model('User', userModel)

Example 3: how to update data subdocument array in mongoose

// mongodb operation
db.getCollection('profilesservices').update({
  _id: ObjectId("6037ad8ac8f713f1d31abe38"), 
 "workExperience._id": ObjectId("6037ad8ac8f713f1d31abe39")}, 
   { $set: { "workExperience.$.companyName": "bukalapak" }
   
})


//sample data
}
    "profileId" : "Sa4Dq9Xuw",
    "photo" : "https://res.cloudinary.com/coding-street-art/image/upload/v1614261651/yxnvpazindsvz6lfst3m.jpg",
    "gender" : "pria",
    "birthDate" : ISODate("1997-03-19T17:00:00.000Z"),
    "status" : "mahasiswa",
    "nationality" : "indonesia",
    "aboutMe" : null,
    "resume" : "https://res.cloudinary.com/coding-street-art/raw/upload/v1614261653/bemkbknvhzknxffmala2.doc",
    "skills" : [ 
        "javascript", 
        "typescript", 
        "react", 
        "vuejs", 
        "express.js", 
        "nodejs"
    ],
    "userId" : "602e8f43c0e227e6cb80bc56",
    "workExperience" : [ 
        {
            "companyName" : "bukalapak", //before valie is bukopin
            "jobPosition" : "data entry",
            "startDate" : ISODate("2015-02-14T17:00:00.000Z"),
            "endDate" : ISODate("2017-07-27T17:00:00.000Z"),
            "workInformation" : "",
            "_id" : ObjectId("6037ad8ac8f713f1d31abe39")
        }, 
        {
            "companyName" : "procar international finance",
            "jobPosition" : "general affair",
            "startDate" : ISODate("2015-02-14T17:00:00.000Z"),
            "endDate" : ISODate("2017-07-27T17:00:00.000Z"),
            "workInformation" : "",
            "_id" : ObjectId("507f1f77bcf86cd799439011")
        }
    ],
    "education" : [ 
        {
            "institutionName" : "unindra",
            "educationDegree" : "sarjana",
            "fieldStudy" : "tehnik informatika",
            "startDate" : ISODate("2015-03-24T17:00:00.000Z"),
            "endDate" : ISODate("2020-03-24T17:00:00.000Z"),
            "educationInformation" : "",
            "_id" : ObjectId("6037ad8ac8f713f1d31abe3a")
        }
    ],
    "appreciation" : [],
    "volunteerExperience" : [],
    "__v" : 0
}

Example 4: mongoose update array in object

Person.findOneAndUpdate({_id: id}, 
{ 
  "$set": {[`items.$[outer].${propertyName}`]: value} 
},
{ 
  "arrayFilters": [{ "outer.id": itemId }]
},
function(err, response) {
  ...
})

Tags:

Misc Example