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

时间:2017-11-22 18:30:19

标签: node.js mongodb aggregation-framework lookup

我的成绩模型是:

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,               更新时间:2017-11-21T08:26:38.413Z,               createdAt:2017-11-21T08:26:38.413Z,               gID:5a13e33e931f7561b85d083f,               等级:20,               类型:2,               __v:0,               myCustomResut :: []},             {_id:5a13e78e4fac5b61ecdbd9ab,               更新时间:2017-11-21T08:45:02.517Z,               createdAt:2017-11-21T08:45:02.517Z,               gID:5a13e78e4fac5b61ecdbd9aa,               等级:20,               类型:2,               __v:0,               myCustomResut :: []}]

2 个答案:

答案 0 :(得分:0)

检查您的收藏是否真的People。根据经验,我知道人们用大写字母创建了一个集合,但在他们的数据库中却是小的。因此,请检查它是否不是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 =新架构({ gID :{type:Schema.Types.ObjectId,ref:   '人物'}

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

  

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

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

答案 1 :(得分:0)

尽量写集合名称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);
      }
});