gpt4 book ai didi

node.js - NodeJS, Mongoose : How to get related data using mongoose

转载 作者:行者123 更新时间:2023-12-03 09:19:03 25 4
gpt4 key购买 nike

我有 2 个集合,它们是一对多关系。如何使用 Mongoose 获取相关数据作为嵌套文档?

我有 2 个模式,它们是这样相关的..

var userSchema = mongoose.Schema({
name : String,
age : Number,
});

var postSchema = mongoose.Schema({
title: String,
body: String,
user: {type: mongoose.Schema.Types.ObjectId, ref:'User'}
});

并且mongodb中有数据..

//user:
{
_id:"5694934cab2816601db06291",
name:"John",
age:16
},
{
_id:"5694934cab2816601db06292",
name:"Kim",
age:61
}

//post :
{
_id:"569494e5ab2816601db06293",
title:"hi",
body:"nice to meet you",
user:"5694934cab2816601db06291"
},
{
_id:"569494e5ab2816601db06294",
title:"hello",
body:"how are you",
user:"5694934cab2816601db06292"
}

使用 Mongoose 获得这样的结果的最佳方法是什么?

{
_id:"569494e5ab2816601db06293",
title:"hi",
body:"nice to meet you",
user:{
_id:"569494e5ab2816601db06294",
name:"John",
age:16
}
},
{
_id:"569494e5ab2816601db06294",
title:"hello",
body:"how are you",
user:{
_id:"569494e5ab2816601db06292",
name:"Kim",
age:61
}
}

最佳答案

您可以通过填充用户来完成此操作。

您可以尝试在查询中填充用户:

代码:

post.find().populate('User').exec(function(err,post){
console.log(post);
console.log(post.User);
})

关于node.js - NodeJS, Mongoose : How to get related data using mongoose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34894293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com