[英]How to get full data from mongoose when schema has reference
这是架构。 我的前端同时需要 [内容、姓名、电子邮件]。 如何获取这三个数据并同时渲染到前端? 你能提供一个示例JS代码来做到这一点吗?
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
}
});
const PostSchema = new mongoose.Schema({
author: {
type: Schema.Types.ObjectID, ref:'User'
},
content:{
type: String
}
});
请尝试以下代码,您可以使用 populate 从参考中获取数据:
post.find()
.where("field")
.in([criteria])
.populate("author")
.exec(function (e, posts) {
if (e) {
//do error handling here
}
if (posts) {
return posts;
}
});
或创建帖子 model 创建作者 model
post.find()
.where("field")
.in([criteria])
.populate({
path: 'author',
model: authorModel
)}
.exec(function (e, posts) {
if (e) {
//do error handling here
}
if (posts) {
return posts;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.