Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

451
Views
Multiple async queries in nodejs (mongoose)

I am a nodejs newbie. I have two simple models, User and Story. Here is what I want to do:

  • I want to retrieve all stories that have {status:"public"} and store it in an array called retrievedStories.
  • Then for each story I want to use its "user" field (which contains the object id of the user) to lookup the name of the user from User
  • Then add a new key in each element of retrievedStories called authorName with the name of the user.

Here are the models:

const UserSchema = new mongoose.Schema({
    googleId: {
        type: String,
        required: true
    },
    displayName: {
        type: String,
        required: true
    },
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },
    image: {
        type: String,
    },
    createdAt: {
        type:Date,
        default: Date.now()
    }
})

const StorySchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
        trim: true
    },
    body: {
        type: String,
        required: true
    },
    status: {
        type: String,
        default: 'public',
        enum: ['public', 'private']
    },
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    createdAt: {
        type:Date,
        default: Date.now()
    }
})

And here is what I tried, but doesn't work. The stories are retrieved but the authorName is not added. Any help (possibly a better way to do this?) will be highly appreciated!

router.get('/',async (req,res)=>{
    try {
        const retrievedStories = await Story.find(
            {status: "public"}
            )
        await Promise.all(retrievedStories.map(async (story) =>{
            const author = await User.findById(story.user)
            story.authorName = author.displayName
        }))

        return res.json(retrievedStories)
        
    } catch (error) {
        console.log(error)
    }

})

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can simplify your query by using populate to retrieve User's data:

router.get('/', async (req, res) => {
    try {
      const retrievedStories = await Story.find({ status: 'public' })
        .populate('user')
        .exec();
      return res.json(retrievedStories);
    } catch (error) {
      console.log(error);
    }
  });  

You can then access User's displayName data on each Story by accessing story.user.displayName.
For more information on query population see the official docs.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!