I have a server setup with nodejs/express and I'm also using mongodb and mongoose. I was following some tutorials and adapting to my project which is basically an user database for a web app. The thing is, when updating a property of my document User I'm using two different ways to do so: one by a dot notation + assignment and the other using the mongoose model method findByIdAndUpdate().
I've searched for other questions and I just found different questions here and here using these solutions but I couldn't find any comparison as to when should I use one instead of the other, can someone explains this, please?
My model schema:
const mongoose = require('../../db');
const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true,
},
email: {
type: String,
unique: true,
required: true,
lowercase: true,
},
password: {
type: String,
required: true,
select: false,
},
score: {
type: Number,
required: true,
default: 0
},
authToken: {
type: String,
select: false
},
authTokenExpires: {
type: Date,
select: false
},
passwordResetToken: {
type: String,
select: false
},
passwordResetTokenExpires: {
type: Date,
select: false
},
createdAt: {
type: Date,
default: Date.now,
},
});
A request I'm using to "forgot password" case in which I supply a resetPassword token (using .findByIdandUpdate()):
const express = require('express');
const User = require('../models/User');
const router = express.Router();
router.post('/forgot_password', async (req, res) => {
const { email } = req.body;
const user = await User.findOne({ email }).select('+password');
try {
await User.findByIdAndUpdate(user._id, { //First way of updating document
'$set': {
passwordResetToken: token,
passwordResetExpires: now,
}
});
catch (err) {
return res.status(400).json({ error: 'Recover password process failed. Please try again' })
}
});
And here it's another request to actually reset the password (using dot notation assignment):
const express = require('express');
const User = require('../models/User');
const router = express.Router();
router.post('/reset_password', async (req, res) => {
const { email, token, password } = req.body;
const user = await User.findOne({ email }).select('+passwordResetToken passwordResetTokenExpires');
try {
const now = new Date();
if (now > user.passwordResetExpires) {
return res.status(400).json({ error: 'Token expired, please generate a new token' })
}
user.password = password; //Second way of updating document
user.passwordResetExpires = null;
await user.save();
return res.send();
}
catch (err) {
console.log(err)
return res.status(400).json({ error: 'Reset password process failed. Please try again' })
}
});