I've implemented promises into mongoose but I'm receiving duplicate log entries and I'm not sure if it's the expected output and if so, why?
I run the below function, only once during an if statement.
const isUsernameTaken = (username) => {
let isTaken;
const promise = User.find({username: username}, (err, doc) => {
if(doc.length) {
isTaken = true;
} else {
isTaken = false;
}
}).exec();
promise.then(() => {
return isTaken;
});
}
mongoose debug output
Mongoose: users.find({username: 'test'}, {projection: {}})
Mongoose: users.find({username: 'test'}, {projection: {}})
true
vs what I would expect
Mongoose: users.find({username: 'test'}, {projection: {}})
true
It looks like using a callback for find
, as well as calling exec()
is sending the request twice... Putting the callback inside of promise.then(...)
should fix it:
const isUsernameTaken = (username) => {
User.find({username: username})
.exec()
.then(doc => doc ? true : false)
.catch(err => console.log(err));
}