I am trying to check if a record exists in MongoDB using mongoose. For that I am using the function findOne(). But even if the record/document does not exists the query returns a non null value. How to use this function or any other way to check if a document exists? My code is:
var req_username = "";
var req_password = "";
const insertUserIntoDatabase = (requestBody) => {
req_username = requestBody.username;
req_password = requestBody.password;
connectToDatabase();
if (doesUserExistAlready()==true) {
console.log("user already there");
}else{
insertUser();
}
}
const connectToDatabase = () => {
mongoose.connect("mongodb://localhost/my_database",
{useNewUrlParser:true});
}
const doesUserExistAlready = () => {
const doc = user.findOne({username:req_username});
if (doc == null) {
return false;
}else{
return true;
}
}
const insertUser = () => {
var newUserDoc = new user();
newUserDoc.username = req_username;
newUserDoc.password = req_password;
newUserDoc.save();
}