【问题标题】:Mongoose findOne.populate scope issueMongoose findOne.populate 范围问题
【发布时间】:2019-07-14 23:00:27
【问题描述】:

currentUser.follow 中有一组用户 ID。每个用户都有 postSchema 的 referenceId 的帖子。现在我想填充每个用户的帖子并将其存储在数组 [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
});

用户架构

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

【问题讨论】:

    标签: javascript node.js express mongoose


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 2014-11-25
      • 2014-12-28
      • 1970-01-01
      • 2020-03-04
      • 2010-11-09
      • 2011-01-08
      相关资源
      最近更新 更多