how to handle promise properly in working with mongodb? [duplicate] - mongodb

This question already has answers here:
How do I access previous promise results in a .then() chain?
(17 answers)
Closed 4 years ago.
I am creating user creation page using mongodb and node. After getting name, email and password, I tried to hash password and save then into mongodb. I could have followed the best practice by using async and await. However I wanted to understand Promise more. So, I tried the following, but at some point I got stuck. Here, used bcrypt for stroing password safely, the steps are 1) bcrypt.getSalt 2) bcrypt.hash 3) create user with new password 4) save it to mongodb. If you look at the following codes, the steps are implemented with those steps. But, when saving user into mongodb, user is out of scope. My question here is how to implement them in the right way with Promise. Could you give me some good example for it? I am beginner programmer, so just want to learn this from expert. so I came to post this.
router.post("/", (req, res, next) => {
bcrypt
.genSalt(10)
.then(salt => {
console.log(`Salt: ${salt}`);
return bcrypt.hash(req.body.password, salt);
})
.then(hash => {
console.log(`Hash: ${hash}`);
return new User({
name: req.body.name,
email: req.body.email,
password: hash
});
})
.then(user => {
console.log(`User: ${user}`);
return User.findOne({ email: user.email }).exec();
})
.then(function(err, found_user) {
if (err) {
return next(err);
}
if (found_user) {
console.log("found user");
} else {
user.save(function(err) {
if (err) {
return next(err);
}
res.redirect(user.url);
});
}
})
.catch(err => console.error(err.message));
});

Why do you need to pass new User? It is not an async operation in mongoose. It just creates a new instance of your model. You can just refactor your code into something shorter like this:
router.post("/", (req, res, next) =>
User.findOne({ email: user.email }).exec().then(user => {
if(user) {
console.log("found user")
next()
} else {
return bcrypt
.genSalt(10)
.then(salt => bcrypt.hash(req.body.password, salt))
.then(hash => {
var user = new User({
name: req.body.name,
email: req.body.email,
password: hash
});
return user.save().exec()
}).then(user => {
// user is saved do whats next
next()
})
}
}).catch(err => console.error(err.message));
)

Related

Create new document if there is not document with same name mongoose

var userSchema = mongoose.Schema({
username: { type: String},
email: String,
password: String,
tasks: [String]
});
I want to create a new user document only if there is no another user with the same name.
What the best way to do that?
this is my implementation currently :
router.post('/', async function(req, res, next) {
use let user= await User.findOne({ name: req.body.name})
if (user) {
if (req.body.name == user.name) {
// return new Error("User exists!"));
}
User.create(req.body, function (err, newuser) {
if (err) {
console.log(err);
return next(err);
}
res.json(newuser);
});
}
Another question about mongoDB collections:
Should I open new collection ( and schema) for 'task' property?
It has only 1 field - the task itself in type string.
Your current implementation is the way to go, you find the user, if none is found, you create a new one.
I refactored your code a little bit, here's how it would look like:
router.post('/', async function (req, res, next) {
try {
const user = await User.findOne({ name: req.body.name });
if (user) {
return res.json(user);
}
const newUser = await User.create(req.body);
return res.json(newUser);
} catch (err) {
console.log(err);
return next(err);
}
});
As to your second question, if you're sure that the task will always be a simple string and you won't need more data in there, it's better to keep it embedded within the document.
It's likely that you'll need to extend functionalities for tasks, and add more data such as a status, deadline, maybe subtasks, in which case it's better to separate it in a different collection.
This series of articles is probably a good place to quickly learn a rule of thumb on how to design your schemas.

How do you validate password using mongoose for mongoDB in an express app for logging in a user?

I am trying to have a user log in by their email and password. MongoDb docs shows hashing the password with bcrypt in the user model. It also provides a nice way to validate the password in the model as well. My problem is how to I use that validation from the "controller"? I am very aware "if (req.body.password === user.password)" will not work because one is hashed and the other is not.
I have been searching for answers for hours and can't seem to find that connection on how I use that "UserSchema.methods.comparePassword" method in my post request to log in. This isn't completely a real log in, just trying to get the password to validate and send back a key once logged in. Here are the docs: https://www.mongodb.com/blog/post/password-authentication-with-mongoose-part-1
// This is my UserModel
let mongoose = require('mongoose'),
Schema = mongoose.Schema,
bcrypt = require('bcrypt'),
SALT_WORK_FACTOR = 10
var hat = require('hat');
let UserSchema = new Schema({
email: {
type: String,
required: true,
index: {
unique: true
}
},
password: {
type: String,
require: true
},
api_key: {
type: String
}
});
UserSchema.pre('save', function(next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
user.api_key = hat();
next();
});
});
});
UserSchema.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', UserSchema);
// This is the sessions.js
let UserModel = require('../../../models/user.model');
var express = require('express');
var router = express.Router();
router.post('/', (req, res, next) => {
UserModel.findOne(
{
$or: [
{ email : req.body.email }
]
}
)
.then(user => {
if (req.body.password === user.password) {
res.setHeader("Content-Type", "application/json");
res.status(200).send(JSON.stringify({
"api_key": `${user.api_key}`
}));
} else {
res.status(404).send("Incorrect email or password")
}
})
.catch(error => {
res.setHeader("Content-Type", "application/json");
res.status(500).send({error})
})
})
module.exports = router
If I just find user by email, everything works fine. Just need to figure out how to use the compare password method in the user model. Thanks!
Maybe have something like this in your model:
User = require('./user-model');
.......
User.findOne({ username: 'jmar777' }, function(err, user) {
if (err) throw err;
user.comparePassword('Password123', function(err, isMatch) {
if (err) throw err;
console.log('Password123:', isMatch); // -> Password123: true
});
........
Other resources:
http://devsmash.com/blog/password-authentication-with-mongoose-and-bcrypt
https://www.abeautifulsite.net/hashing-passwords-with-nodejs-and-bcrypt
https://medium.com/#mridu.sh92/a-quick-guide-for-authentication-using-bcrypt-on-express-nodejs-1d8791bb418f
Hope it helps!

Mongoose: findOneAndUpdate pre hook not working

I've searched about this issue and all the solutions that I've found didn't actually work. I'm currently using this function to encrypt the password before storing in the database but even though the values are being changed when logging this, the password isn't stored like it was changed in the function.
UserSchema.pre('findOneAndUpdate', function(next) {
const update = this.getUpdate();
if (!_.isEmpty(update.password)) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(update.password, salt, (err, hash) => {
this.getUpdate().password = hash;
next();
})
})
}
next();
});
I've also tried to change the value of this._update.password instead but it didn't work either. I've also tried using $set or even using a post hook but none of them helped either. What am I doing wrong?
I just tested this locally with:
var result = Author.findOneAndUpdate({ _id: <some id> }, { password: '111' }).exec()
and this pre hook:
AuthorSchema.pre('findOneAndUpdate', function(next) {
this._update.password = 'BBB'
next();
});
Password was saved as BBB
Author schema has a password field which is type: String
I am on 3.6.5
In your bcrypt case you have also an extra next() without else which is messing you up ... should be:
UserSchema.pre('findOneAndUpdate', function(next) {
const update = this.getUpdate();
if (!_.isEmpty(update.password)) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(update.password, salt, (err, hash) => {
this.getUpdate().password = hash;
next();
})
})
} else {
next();
}
});
user.pre('findOneAndUpdate', function(next){
const user=this.getUpdate().$set;
if(!user.password){
next();
}
else{
bcrypt.genSalt(10, function (err, salt) {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, null, function (err, hash) {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
}
})

Bcrypt returns false on login

I know this question has been asked many times but I cannot find an answer to my problem both here or on github. I have a login handler which compares hashed password from db to the the one typed by the user on login. bcrypt.compare almost always returns false. I say almost because sometimes it just starts working and it always works after I register user. I am trying to find what is wrong with my code but cant figure it out. Any help is highly appreciated.
mongoose pre save
userModel.schema.pre('save', function(next) {
let user = this;
bcrypt.hash(user.password, 10, null)
.then(hash => {
console.log(hash)
user.password = hash;
user.confirmPassword = hash;
next();
})
.catch(err => res.sendStatus(404));
});
login handler
exports.loginUser = (req, res) => {
let user = new User.model(req.body);
User.model
.find({email: user.email})
.exec()
.then(users => {
if (!users.length) {
res.status(401).json({
message: "Auth failed - user does not exist"
});
} else {
bcrypt
.compare(req.body.password, users[0].password)
.then(result=> {
console.log(user.password, users[0].password)
console.log(bcrypt.hashSync(req.body.password, 10))
if (result) {
const token =
jwt
.sign({ email: users[0].email, id: users[0]._id },
'secretKey', { expiresIn: "1h"});
res.status(200).json({
message: "Auth success - logged in",
token,
users
});
} else {
res.json('not working');
}
})
.catch(err => res.status(401).json({message: "Auth failed"}));
}
});
};
register handler
exports.registerUser = (req, res) => {
let user = new User.model(req.body);
if(user.email) {
User.model
.find({email: user.email})
.exec()
.then(docs => {
if (!docs.length) {
if (user.password !== user.confirmPassword) {
return res.status(404).json('passwords do not match');
}
user.save(function (err, user) {
if (err) return (err);
});
console.log('user saved');
res.sendStatus(200);
} else {
res.status(404).json('user exists');
}
})
.catch(err => res.sendStatus(404).json(res.body));
} else {
res.status(404).json('user name required');
}
};
The problem might be that you generate a new password each time the user is saved. You should skip this though.
userModel.schema.pre('save', function(next) {
let user = this;
if(!user.isModified("password")) return next();
bcrypt.hash(user.password, 10, null)
.then(hash => {
console.log(hash)
user.password = hash;
user.confirmPassword = hash;
next();
})
.catch(err => res.sendStatus(404));
});
Just a shot in the dark though. under the assumption something got changed and this was called again, because you stated it is working sometimes.

Rollback Transaction for Multiple Models in Waterline ODM in Sails (For Mongo DB )

I am using Sails and Waterline ORM with Mongo Database .
I have two models User and Profile with One to One relationship.
Below is the code I've written for Transaction with Rollback logic. I think there can be a much better logic than this as the current logic is very clumsy.
Questions :
Does Waterline or Sails provide any functionality for Rollback purpose?
Is there any better way of doing this ?
User.create(newUser).then(function (data) {
var newProfile = {
displayName: data.name,
email: data.email,
user: data._id
}
return Profile.create(newProfile);
}).then(function (profileData) {
sails.log.info("Profile Data " + JSON.stringify(profileData));
// Update the user with Profile Info
User.update(newUser._id, {profile: profileData._id}).then(function (updatedUser) {
return updatedUser;
}, function (err) {
// TODO Rollback logic if the User Updation Fails
})
}, function (err) {
sails.log.error("Failed to Create Profile for the User . Deleting the created User");
var criteria = {
email: data.email
}
User.destroy(criteria).then(function (user) {
sails.log.error("Deleted the Created User " + JSON.stringify(user));
throw new Error("ERROR CREATING User");
}, function (err) {
sails.log.error("ERROR DELETING USER");
throw new Error("ERROR DELETING USER", err);
})
});
To question 1 : no.
I would be tempted to do something like this:
async.waterfall([
function(callback){
User.create(newUser).then(function(data){
callback(null, data);
})
.catch(function(err){
callback(err, null, null); // don't need to rollback anything
})
},
function(data, callback){
Profile.create({
displayName: data.name,
email: data.email,
user: data._id
})
.then(function(profile){
callback(null, data, profile)
})
.create(function(err){
callback(err, data._id, null); // only need user's id
})
},
function(userData, profileData, callback){
User.update(userData._id, {profile: profileData._id})
.then(function(updatedUser){
callback(null, updatedUser);
})
.catch(function(err){
callback(err, userData._id, profileData._id); // can roll back both
})
}
], function(err, userData, profileData){
if(err) {
sails.log.error(err);
// do rollback, userData is user's ID, profileData is profile id
// if either one is undefined, then it doesn't exist
} else {
// userData is user object from the last update, return it!
}
})
I don't know if it is better, but it seems more readable, and it handles the errors for any of the three writing phases.