【问题标题】:Mongoose: Aggregation return empty valueMongoose:聚合返回空值
【发布时间】:2020-10-10 01:40:27
【问题描述】:

我正在使用聚合来加入 3 个集合。但是连接的结果是一个空数组[]。 这是我对所有 3 个集合以及聚合查询的模型。 console.log(timetable) 的结果返回 []。我正在使用引用来引用 Timetable 中具有相应集合的字段。

时间表模型

var TimetableSchema = new mongoose.Schema ({

    timeslot: {
        required: true, 
        'type': String,
    },

    classroom :{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Classroom'
    },

    subject :{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Subject'
    },

    teacher :{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'   
    },

    day :{
        type:String, 
        required: true, 
    },

    year :{
        type:String, 
        required: true, 
    },

    session :{
        type:String,
        required:true,
    }


})

课堂模型

var ClassroomSchema = new mongoose.Schema ({


    classroom_name: {
        type:String,
        required:true,
        unique: true,
    },

    classroom_blok:{
        type:String,
        required:true,
    },

    classroom_floor: {
        type:String,
        required:true,
    },


});

主题

var SubjectSchema = new mongoose.Schema ({

    subject_id: {

        required: true, 
        'type': String,
        'default': shortid.generate
    },

    subject_name: {
        type:String,
        required:true,
    },

    subject_darjah:{
        type:String,
        required:true,
    }

});

聚合查询

router.get('/today_absentee/view/:id',function(req,res){
  Teacher.findById(req.session.userId).exec(function (error, user){
    if (error){
      return next(error);
    }else
    {
      Teacher.find({_id:req.params.id }).exec(function(err, teacher){
        if(err)
        {
          return next(err);
        }else
        {
          Timetable.aggregate([

            {
                // This is doing the same thing as the previous .find()
               $match: {  teacher:req.params.id}
            },
            {
              $lookup:{
                  from: "Classroom",       // other table name
                  localField: "classroom",   // name of users table field
                  foreignField: "_id", // name of userinfo table field
                  as: "classroom"         // alias for userinfo table
              }



            },

            {   $unwind:"$classroom" },     // $unwind used for getting data in object or for one record only

            {
              $lookup:{
                  from: "Subject",       // other table name
                  localField: "subject",   // name of users table field
                  foreignField: "_id", // name of userinfo table field
                  as: "subject"         // alias for userinfo table
              }  
            },

            {   $unwind:"$subject" },     // $unwind used for getting data in object or for one record only

            // define some conditions here 
            {
                $match:{
                $and:[{teacher:req.params.id}]
                 }
            },

            // define which fields are you want to fetch
             {   
                $project:{

                    subject_name : "$subject.subject_name",
                    classroom : "$classroom.classroom_name",
                } 
             }
          ]).exec(function(err, timetable) 
          {
            // The query output is such that `classroom.classroom_name`
            // value is unique for each document
            if (err) throw err;
            console.log(currentYear);
            console.log(timetable);
            res.render('creator_content/today_absentee_id',{timetable:timetable,  user:user, teacher:teacher});
          });
        }
      });


    }
  });
});

所有 3 个系列的模型。

【问题讨论】:

    标签: node.js mongodb mongoose ejs


    【解决方案1】:

    在文件顶部导入 mongoose,然后在匹配聚合查询中的任何对象 ID 字段时使用 mongoose.Types.ObjectId()。 我还使用 $addFields 聚合管道添加了 2 个字段(subject_name、classic),然后在下一阶段使用 $project 输出它们。

    const mongoose = require("mongoose");
    
    router.get('/today_absentee/view/:id', function(req, res) {
      Teacher.findById(req.session.userId).exec(function(error, user) {
        if (error) {
          return next(error);
        } else {
          Teacher.find({
            _id: req.params.id
          }).exec(function(err, teacher) {
            if (err) {
              return next(err);
            } else {
              Timetable.aggregate([
    
                {
                  // This is doing the same thing as the previous .find()
                  $match: {
                    teacher: mongoose.Types.ObjectId(req.params.id)
                  }
                },
                {
                  $lookup: {
                    from: "Classroom", // other table name
                    localField: "classroom", // name of users table field
                    foreignField: "_id", // name of userinfo table field
                    as: "classroom" // alias for userinfo table
                  }
                },
                {
                  $unwind: "$classroom"
                }, // $unwind used for getting data in object or for one record only
    
                {
                  $lookup: {
                    from: "Subject", // other table name
                    localField: "subject", // name of users table field
                    foreignField: "_id", // name of userinfo table field
                    as: "subject" // alias for userinfo table
                  }
                },
    
                {
                  $unwind: "$subject"
                }, // $unwind used for getting data in object or for one record only
    
                // define some conditions here 
                {
                  $match: {
                    $and: [{
                      teacher: mongoose.Types.ObjectId(req.params.id)
                    }]
                  }
                },
    
                // Add new field names
                {
                  $addFields: {
                    subject_name: "$subject.subject_name",
                    classroom: "$classroom.classroom_name",
                  }
                },
    
                // define which fields are you want to fetch
                {
                  $project: {
                    subject_name: 1,
                    classroom: 1,
                  }
                }
              ]).exec(function(err, timetable) {
                // The query output is such that `classroom.classroom_name`
                // value is unique for each document
                if (err) throw err;
                console.log(currentYear);
                console.log(timetable);
                res.render('creator_content/today_absentee_id', {
                  timetable: timetable,
                  user: user,
                  teacher: teacher
                });
              });
            }
          });
    
        }
      });
    });

    【讨论】:

    • 仍然返回空数组[]
    • @TaqiuddinShokordey 你解决了这个问题吗?即使使用 mongoose.Types.ObjectId,我也会一直空着
    猜你喜欢
    • 2016-11-16
    • 2021-03-30
    • 2019-04-28
    • 1970-01-01
    • 2022-10-13
    • 2016-02-17
    • 1970-01-01
    • 2021-10-25
    • 2015-07-23
    相关资源
    最近更新 更多