nodejs(mongoose)中的多个异步查询

Multiple async queries in nodejs (mongoose)

我是一个nodejs新手。我有两个简单的模型,用户和故事。这是我想要做的:

以下是模型:

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()
    }
})

这是我尝试过的方法,但没有用。检索了故事,但未添加 authorName。任何帮助(可能是更好的方法?)将不胜感激!

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)
    }

})

您可以使用 populate 检索 User 的数据来简化查询:

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);
    }
  });  

然后您可以通过访问 story.user.displayName.
访问 User 在每个 Story 上的 displayName 数据 更多查询人口见官方docs.