javascript - Mongoose findOne.populate 范围问题

标签 javascript node.js express mongoose

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

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

User Schema

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

Post Schema

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

最佳答案

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

有一种更好的方法可以使用 $in 运算符和 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);
  }
});

关于javascript - Mongoose findOne.populate 范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57027445/

相关文章:

javascript - 如何在同一个html页面中使用2个angularjs应用程序?

node.js - 从 Jade 内部获取用户代理

node.js - 我应该如何攻击 JavaScript 重堆栈中的大型 GroupBy 记录集?

node.js - 将 Auth0 集成到 Node & Express 应用程序中

Javascript OOP 子类帮助和结构

javascript - 当每个 jQuery Ajax 请求完成时得到响应?

javascript - 如果输入是 JavaScript 中的数组数组,如何传播参数

node.js - 如何在node.js中安装Strongloop api并可以使用loopback

javascript - 使用 Cowboy 作为 Express JS 的 HTTP 网络服务器

node.js - 如何在实时服务器中配置 webpack