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
});

4
3
Phoenix Logan 186120 points

                                    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)

4 (3 Votes)
0
Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Relative searches
mongoose subdocuments update record mongoose subdocuments update specific record mongoose updateOne for subdocument mongoose updateOne for subdocment update specific subdocument mongoose how to find and update subdocuments id mongooseh how to find and update subdocuments id mongoose how to find and update subdocuments mongoose mongoose update subdocument field update subdocuments mongoose mongoose update subdocument by filter mongoose change in subdocument mongoose document update with subdocument in node mongoose findone and update subdocument how to update sub document mongoose mongoose updateone subdocument mongoose update collection with subdocuments mongoose update to subdocument by criteria mongoose js update document in subdocuments collection update subdocumetn mongoose mongoose update sub document update express mongoose sub documents update mongoose with subdocuments MONGOOSE UPDATE WITH SUBDOCUMENTS update subdocument to object mongoose mongoose update subdocument to array express mongoose find and add new subdocument mongoose return only ids insertmany mongoose findbyidandupdate update subdocuments mongoose findbyidandupdate update embedded subdocumentd mongoose update element in array mongoose find and update subdocument array mongoose get items from subdocument mongoose update attribute updateone return document mongoose mongoose get subdocument atualizar subdocumento mongoose updating elemnt of subdocument update single subdocument key value using mongodb upsert subdocs mongoose how to embed subdocument in node js mongoose find subdocument in array by id npm mongoose update subdocuments mongoose update subdocuments by id mongoose update linked subdocument mongoose how to update array of subdocuments using find by id and update mongoose mongoose update child document mongoose updating subdocuments update a subdocument mongoose mongoose update subdocument array element updating subdocument mongoose how to edit child schema in mongodb how to updata a subdoc mongoose how to update subdocument array in mongoose update to subdocument didn't update parent document mongoose add subdocument to document is a patch or post mongoose controller for subdocument update select subdocument in an array to update mongoose set subdocument mongoose findone "subdocument" match multiple fields route for create subdocument and update parent document mongoose express mongoose update a subdocument mongoose update subdocument example mongoose find and update subdocument best practices update mongoose subdocumente especifico mongoose update subdocument by property mongoose find in subschema mongoose find one and update subdocument mongoose create document with subdocument of many objects, how to update a single object in that subdocument $set in mongoose subdocument update or create subdocument mongoose mongoose update subdocument update subdocument mongoose i am not able to add multiple value in subdocument in postman api i am not able to add multiple objects in subdocument in postman mongoose find in array subdocument data mongoose update array of subdocuments mongoose update subdocument array object mongoose js update document in subdocument collection mongoose update subdocument array mongoose update data subdocument mongoose update subdocument by id
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source