Example 1: mongoose modify all elements in array
db.collection.update({
"_id": "password"
},
{
"$inc": {
"waitlist.$[].queue_place": -1
}
})
Example 2: mongoose save or update
findByIdAndUpdate(_id, { something: 'updated' }, { upsert: true });
Example 3: mongoose update subdocument by id
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);
});
});
BlogPost.findOneAndUpdate({_id: req.params.postId}, {$push:{ subDoc: req.body }}, (err, doc) => {
});
Example 4: updating an array of object in mongoose
Person.update(
{
_id: 5,
grades: { $elemMatch: { grade: { $lte: 90 }, mean: { $gt: 80 } } }
},
{ $set: { "grades.$.std" : 6 } }
)
Example 5: update query in mongoose
var conditions = { name: 'bourne' }
, update = { $inc: { visits: 1 }}
Model.update(conditions, update, { multi: true }).then(updatedRows=>{
}).catch(err=>{
console.log(err)
})
Example 6: 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]
})
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);
}
});
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)