[英]Schema field is not being populated using mongoose populate
這是我的 model:
const postSchema = Schema({
_id: Schema.Types.ObjectId,
name: String,
comments: Array
});
const Post = mongoose.model(“Post”, postSchema);
module.exports = Post;
這是我的代碼向另一個微服務發出請求以填充評論數組,但它是空的,並且沒有被填充:
const UserPost = require(“./PostSchema”);
router.get("/post/list", async (request, response) =>{
try {
let myUserPost = await UserPost.find();
let postComments = await Promise.all(
myUserPost.map((post) =>{
axios.get(`${process.env.COMMENTS_MICROSERVICE_URL}/router/comments/list/comments/by/post/${post._id}`)
.then((resp) => {
resp.data.message.map((comment) =>{
if(String(post._id) === comment.postID){
//console.log("post._id: ", post._id);
/*** Desired, but does not work
return UserPost.findById(post._id).populate('comments').exec(); */
//The following alternative (embedding) works but adds the data to array
/***return UserPost.findByIdAndUpdate(post._id, {$addToSet: {"comments": comment}}, (err, data) =>{
err ? console.log(err) : console.log("aa: ", data);
}); */
}else{
console.log("no")
}
});
})
})
);
return response.status(200).json({message: myUserPost});
}catch(err){
return response.status(400).json({message: `${err}`});
}
});
go 關於這個的最佳方式是什么,並讓它填充評論字段?
ref
屬性:const postSchema = Schema({
_id: {
type: Schema.Types.ObjectId,
ref: 'comments'
},
name: String,
comments: Array
});
const Post = mongoose.model(“Post”, postSchema);
module.exports = Post;
populate
方法之后調用exec
。UserPost.findById(post._id).populate('comments').exec();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.