mongoose get subdocument code example

Example 1: populate subdocument mongoose

ProjectMetadata.findOne({id:req.params.prjId})
    .populate(
        [{
        path:'tasks',
        model:TaskMetadata,
        populate:[{
            path:'assigned_to',
            model:User,
            select:'name employee_id'
        },
        {
            path:'priority',
            model:Priority,
            select:'id title'
        }],
        select:"task_name id code assign_to stage priority_id"
    },
    {
        path:'client',
        model:Client,
        select:"client_name"
    },
    {
        path:'prjct_mgr',
        model:User,
        select:"name"
    },
    {
        path:'acc_exec',
        model:User,
        select:'name employee_id'
    },
    {
        path:'poc',
        model:User,
        select:'name employee_id'
    },
    {
        path:'prj_type',
        model:ProjectType,
        select:"type -_id"
    }

])

Example 2: mongoose nested object without id

var subSchema = mongoose.Schema({
    //your subschema content
},{ _id : false });

Example 3: 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)