I am just learning Mongoose and NodeJS. Attempting my own project after finishing a tutorial.
I have two Models: "Flat" (containing flat numbers) and "User" (users owning the Flats).
var flatsSchema = new mongoose.Schema({
flat: String,
users:[{
userId: String,
username: String,
userType: String //owner or tenant
}]
});
var Flat = new mongoose.model("Flat", flatsSchema);
var userSchema = new mongoose.Schema({
username: String,
flatsRegistered: [{
flat: String,
userType: String //owner or tenant
}]
});
var User = new mongoose.model("User", userSchema);
A User may own multiple Flats, and in each Flat, there can be multiple users.
In the "Flat" model, I have the users living in each flat in the "users" property. I also have flats owned by the users in the flatsRegistered property of "User" model.
Now when a user logs in to his webpage - I want to pass all the details of the flats he is registered to - with all the other users in those flats.
I tried the
flatsRegistered.foreach((userFlat) => {
Flat.findOne({ flat: userFlat }, function (err, flatFound) {
if (!err) {
console.log(flatFound.users) //assign flatFound.users to a variable which i pass to webpage using ejs
}
});
}
Trouble is the foreach loop completes before the Flat.findOne can complete. Is there any way to force Flat.findOne to complete before foreach can continue? After reading up things, I am discovering concepts of async/await and promise - but I really don't know how to use those (and even if they are applicable). Please help.