NodeJS、Mongoose:如何使用mongoose获取相关数据 [英] NodeJS, Mongoose: How to get related data using mongoose

查看:35
本文介绍了NodeJS、Mongoose:如何使用mongoose获取相关数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 2 collections and they are in one-to-many relationship. How can i get related data as nested document using mongoose?

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

I have 2 schemas and they are related like this..

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里面有数据..

and there are data in 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"
}

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

What is the best way to get results like this using 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
  }
}

推荐答案

您可以通过填充 User.

You can do this by populating User.

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

You can try to populate User in your query :

代码:

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

这篇关于NodeJS、Mongoose:如何使用mongoose获取相关数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆