javascript - 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);
解决方案
因为User.findById
是异步的,所以第二个console.log(userArray);
将在结果推送到之前执行userArray
。
有一种更好的方法可以使用$in
operator 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);
}
});
推荐阅读
- asynchronous - Ocaml / 异步套接字问题
- error-handling - 如何使用 Serde 解析可能无法反序列化的字段,而不会导致整个反序列化失败?
- javascript - Codeigniter 中带或不带斜杠的 Ajax 数据调用出错
- javascript - 选择选项上的 for 循环不起作用
- c - STM32 LwIP netconn_write传输结构的问题
- c# - 当玩家(另一个 2D 精灵)统一进入其触发器时,我如何让我的硬币(一个 2D 精灵)自毁?
- django - 如何使用 Google Drive 为部署在 Heroku 中的 Django 应用程序保存媒体文件?
- android - Android Studio 中突出显示的 RxAndroid `Observable...subscribe`
- android - XML重复属性android studio
- python-3.x - WTForms HiddenField() POST 后不包含任何数据