node.js - 在猫鼬模式中填充嵌套对象的字段
问题描述
我有这两个模型
var postSchema = new Schema({
content : String,
author : [{
user : {
type: Schema.ObjectId,
ref: 'user'
},
bool: Boolean
}]
});
var userSchema = new Schema({
name : String
});
我正在尝试使用用户名填充 Post 而不是仅显示 [Object] 或 id 如果 i .toString 它
我现在得到的是:
{ author: [ [Object], [Object], [Object] ],
_id: 5aedc4d3c534213279faec79,
content: 'hello',
__v: 0 } ]
使用 .toString() 我得到
{ author:
[ { _id: 5aedc364ce3b022d4ff74922,
user: 5aedb9e47e055d1ac26aa572,
bool: true } ]
我想要的是 :
{ author:
[ { _id: 5aedc4d3c534213279faec7c,
user: "Some name here", //( name instead of user _id )
bool: true },
{ _id: 5aedc4d3c534213279faec7b,
user: "Some name here",
bool: false },
{ _id: 5aedc4d3c534213279faec7a,
user: "Some name here",
bool: true } ],
_id: 5aedc4d3c534213279faec79,
content: 'hello',
__v: 0 }
这可能吗 ?
解决方案
您可以使用带有嵌套语法的填充方法
const Post = mongoose.model('Post', postSchema);
const User = mongoose.model('User', userSchema);
Post
.find({})
.populate({path:'author.user', 'model':'User'})
.exec((err, posts) => {
if (err) return next(err);
posts.forEach(post => {
console.log(JSON.stringify( post, null, 2) ); // spacing level = 2
}
});
将为每个帖子输出(这不完全是您所需要的,但希望您可以在User
格式上有灵活性
{
_id: 5aedc4d3c534213279faec79,
content: 'some content',
author: [
{
user: {_id: 5aedc4d3c534213279faec7c, "user name here"}
bool: true
},
{
user: {_id: 5aedc4d3c534213279faec7b, "user name 2 here"}
bool: true
}
__v: 0
}
参考 mongoose.populate http://mongoosejs.com/docs/populate.html
推荐阅读
- excel - 如何将相邻单元格中的日期分组在一起以创建一个范围?
- docker - 无法访问或扩展 AWS Batch 托管 EC2 Docker 上的完整实例存储
- typescript - TypeScript 中的通用 ConsList 类型错误
- github - 从 github 操作运行时 aocl 命令无法正常工作
- javascript - 导出的对象在通过 call() 传递给另一个导出函数时给出未定义
- c# - 绑定到模型类的 WPF 文本框,从更新的属性更新文本框,但在框中键入不会更新属性或文本值
- python - 如何在 Kivy 窗口顶部的画布上放置一个矩形?
- tsql - Azure Synapse 无服务器 - Azure Synapse 无服务器池中的流加载镶木地板意外结束
- reactjs - 启用了 PropTypes linting 的功能组件上的 mapStateToProps
- awk - 识别分层文件bash脚本中的行