首页 > 解决方案 > Mongoose findOne.populate 范围问题

问题描述

currentUser.follow 中有一组用户 ID。每个用户都有 postSchema 的 referenceId 的帖子。现在我想填充每个用户的帖子并将其存储在数组 [userArray] 中。但由于范围问题,该数组仍然为空。请告诉我如何在 Array[userArray] 中获取所有用户的帖子

应用程序.js

app.get("/", isLoggedIn, function(req, res){
    var currentUser =req.user;
    var userArray=[];
    for(let fol of currentUser.follow){
        User.findById(fol).populate("posts").exec(function(err, user){
            if(err){
                console.log(err);
            }else{
                console.log(user);    // a user with populated posts
                userArray.push(user);
                console.log(userArray);  //stores user but posts is not populated
            }
        });
    }
    console.log(userArray);  // empty array
});

用户模式

var mongoose =require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
    name: String,
    email: String,
    username: String,
    password: String,
    posts: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Post"
        }
    ],
    follow: [String]
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);

后架构

var mongoose =require("mongoose");

var PostSchema = new mongoose.Schema({
    text: String,
    image: String,
    author:{
        id:{
            type: mongoose.Schema.Types.ObjectId,
            ref : "User"
        },
        username: String
    },
    createdAt: {type:Date, default:Date.now}
});
module.exports= mongoose.model("Post", PostSchema);

标签: javascriptnode.jsexpressmongoose

解决方案


因为User.findById是异步的,所以第二个console.log(userArray);将在结果推送到之前执行userArray

有一种更好的方法可以使用$inoperator and来做到这一点async/await

app.get("/", isLoggedIn, async function(req, res){
  try {
    var currentUser = req.user;
    var userArray = await User.find({_id: {$in: currentUser.follow}}).populate("posts");
    console.log(userArray); 
  } catch(err) {
    console.log(err);
  }
});

推荐阅读