I am trying to copy to a local variable the data of a successfully saved user on monogodb yet not successful.
I initialized a variable called regiseredUser and on the promise function of .save().then(//promise) I tried to save the returned data to regiseredUser regiseredUser = user;
however when I console.log(regiseredUser)
I am getting empty object
let regiseredUser = {}
User.findOne({ email: req.body.email }).then(user => {
if (user) {
return res.status(400).json({ email: "Email already exists" });
} else {
const newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
verified: req.body.verified,
});
newUser.verified = false;
// Hash password before saving in database
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then((user) => {
regiseredUser = user;
res.json(user)}
)
.catch(err => console.log(err));
});
});
console.log(regiseredUser)
I was expecting user to be copied to regiseredUser yet it is not happening