小编Imt*_*ekH的帖子

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

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

我有 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'}
});
Run Code Online (Sandbox Code Playgroud)

并且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"
}
Run Code Online (Sandbox Code Playgroud)

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

{
  _id:"569494e5ab2816601db06293", 
  title:"hi", 
  body:"nice to meet you", 
  user:{
         _id:"569494e5ab2816601db06294",
         name:"John", 
         age:16
  }
},
{
  _id:"569494e5ab2816601db06294",
  title:"hello",
  body:"how are …
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb node.js

2
推荐指数
1
解决办法
3853
查看次数

标签 统计

mongodb ×1

mongoose ×1

node.js ×1