NodeJS,Mongoose:如何使用mongoose获取相关数据

时间:2016-01-20 07:48:07

标签: node.js mongodb mongoose

我有两个系列,他们是一对多的关系。 如何使用mongoose将相关数据作为嵌套文档获取?

我有两个模式,它们就像这样......

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

1 个答案:

答案 0 :(得分:1)

您可以通过填充用户来执行此操作。

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

代码:

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