Mongoose Mongodb querying an array of objects
I changed it to use findOne instead of find and it works now. I am not too sure why this should make a difference. This is the findOne function I used:
User.findOne({'local.rooms': {$elemMatch: {name: req.body.username}}}, function (err, user) {
if (err){
return done(err);
}
if (user) {
console.log("ROOM NAME FOUND");
req.roomNameAlreadyInUse = true;
next();
} else {
req.roomNameAlreadyInUse = false;
console.log("ROOM NAME NOT FOUND");
next();
}
});
findOne
returns a single document, where find
returns a cursor. Once you go through the cursor of find, you are at the end, and there are no more documents.
User.findOne({'local.rooms': {$elemMatch: {name: req.body.username}}}, (err,UserInfo) => {
if (err){
return res.status(400).json({Error:"Something went wrong please try again"})
}
if (UserInfo) {
console.log("ROOM NAME FOUND");
req.roomNameAlreadyInUse = true;
res.json({msg:"Room name found.",userData:UserInfo})
} else {
req.roomNameAlreadyInUse = false;
console.log("ROOM NAME NOT FOUND");
res.json({msg:"Room name not found."})
}
});