NodeJS,MongoDB,聚合函数$lookup结果为空数组[]

NodeJS, MongoDB, Aggregation function with $lookup result is empty array []

我的成绩模型是:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var GradeSchema = new Schema({
gID: {type:Schema.Types.ObjectId,ref: 'People'},
    grade: Number,
    type: Number
}, {timestamps: true});

var Grade = mongoose.model('Grade', GradeSchema);
module.exports=Grade;

人物模型是:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var PeopleSchema = new Schema({
_id: {type:Schema.Types.ObjectId,ref:'Grade' },
    name: String,
    lastName:String,
    phone: String
},{timestamps: true});

var People = mongoose.model('People', PeopleSchema);

module.exports=People;

我的汇总查询是:

Grade.aggregate([

      {$lookup:{ from: 'People', localField:'glD', 
        foreignField:'_id',as:'myCustomResut'}},
]).exec((err, result)=>{
      if (err) {
          console.log("error" ,err)
      }
      if (result) {
          console.log(result);
      }
});

** 但 myCustomResut 是空结果,如 myCustomResut []: ** 这段代码有什么问题?

[ { _id: 5a13e33e931f7561b85d0840, updatedAt: 2017-11-21T08:26:38.413Z, createdAt: 2017-11-21T08:26:38.413Z, gID: 5a13e33e931f7561b85d083f, grade: 20, type: 2, __v: 0, myCustomResut:: [] }, { _id: 5a13e78e4fac5b61ecdbd9ab, updatedAt: 2017-11-21T08:45:02.517Z, createdAt: 2017-11-21T08:45:02.517Z, gID: 5a13e78e4fac5b61ecdbd9aa, grade: 20, type: 2, __v: 0, myCustomResut:: [] } ]

检查你的 collection 是否真的是 People。根据经验,我知道人们用大写字母创建了 collection,但在他们的数据库中它是小写的。因此,请检查它是否不是 people 。它与猫鼬有关。 所以像这样再次尝试聚合:

Grade.aggregate([

      {$lookup:{ from: 'people', localField:'gID', 
        foreignField:'_id',as:'myCustomResut'}},
]).exec((err, result)=>{
      if (err) {
          console.log("error" ,err)
      }
      if (result) {
          console.log(result);
      }
});

你在这里定义了你的字段gID(大写 i):

var GradeSchema = new Schema({ gID: {type:Schema.Types.ObjectId,ref: 'People'}

你在这里写了 glD(小写 L):

{$lookup:{ from: 'People', localField:'glD'

我更新了上面的代码片段,所以再试一次,将 collection 设为 Peoplepeople。但是错的肯定是glD。这对我来说也很棘手,因为如果你像那样阅读代码,它看起来不会有问题。当我去编辑我的答案时,我才意识到这是错误的。

尝试写集合名称 peoples 而不是 people

 Grade.aggregate([

      {$lookup:{ from: 'peoples', localField:'gID', 
        foreignField:'_id',as:'myCustomResut'}},
]).exec((err, result)=>{
      if (err) {
          console.log("error" ,err)
      }
      if (result) {
          console.log(result);
      }
});