1

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.

1 Answer 1

1

Just use for of with await like this:

for (const userFlat of flatsRegistered) {
  const flatFound = await Flat.findOne({ flat: userFlat });
  console.log(flatFound.users) //assign flatFound.users to a variable which i pass to webpage using ejs
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.