【问题标题】:NodeJS, Mongoose: How to get related data using mongooseNodeJS、Mongoose:如何使用 mongoose 获取相关数据
【发布时间】:2016-04-25 23:01:42
【问题描述】:

我有 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"
}

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

{
  _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
  }
}

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

您可以通过填充用户来做到这一点。

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

代码:

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

【讨论】:

    猜你喜欢
    • 2019-07-17
    • 1970-01-01
    • 2013-11-06
    • 2011-11-20
    • 2012-02-12
    • 2018-06-30
    • 2018-05-07
    • 2014-08-12
    相关资源
    最近更新 更多