【问题标题】:get count and merge with response in mongoose获取计数并与猫鼬中的响应合并
【发布时间】:2022-01-21 02:09:44
【问题描述】:

我有一些类似下面的架构。

var studentSchema = new Schema({
    name:{
        type: String,
        required: true
    },
});

var alertSchema = new Schema({
   student_id: {
        type: Schema.Types.ObjectId,
        ref: 'student',
        required: true
    },
    name:{
        type: String,
        required: true
    },
type:{
        type: String,
        required: true
    },
})

我需要通过 student_id 获取警报计数并将其与学生详细信息合并。 结果应该如下所示

[{
    "_id": "61b2e66ddecb23132cc9641c",            
    "name": "studentname1",
    "alertcount": 100,
},
{
    "_id": "61b2e66ddecb23132cc9641c",            
    "name": "studentname2",
    "alertcount": 50,
}]

感谢提前

【问题讨论】:

    标签: node.js mongodb mongoose nestjs


    【解决方案1】:

    您可以在 mongoose 中使用聚合。

    首先更改您的 StudentSchema 以包含 alertCount :

    var studentSchema = new Schema({
        name:{
            type: String,
            required: true
        },
        alertCount : {type : Number , default : 0}
    });
    

    然后在警报模型上使用聚合:

    let alertCounts = Alert.aggregate([
       {$match : {name : student.name }}, // filters all the alerts where name is equal to a particular student's name from Student model
       {$count : "alertCount"}
    ])
    

    这适用于一名学生。您必须将其应用于数据集中的每个学生。你可以使用map函数来实现。

    Student.find({})
    .then(students=>{
      students.map(student=>{
         let alertCounts = Alert.aggregate([
            {$match : {name : student.name }},
            {$count : "alertCount"}
         ])
         student.alertCount = alertCounts.alertCount;
         student.save()
      })
    }
    

    该代码尚未经过测试,我可能需要进行一些小的更改,但我希望这可以帮助您了解如何实现您想要的功能。

    【讨论】:

    • 谢谢,它正在工作。在获取学生详细信息时,我也需要获取这些警报记录。我该怎么做??结果如下 ` [{ "_id": "61b2e66ddecb23132cc9641c", "name": "studentname1", "alertcount": 100, "alerts": [{"_id": "61b2e66ddecb23132cc9641c","name": "alertname1 "}], }, { "_id": "61b2e66ddecb23132cc9641c", "name": "studentname2", "alertcount": 50, "alerts": [{"_id": "61b2e66ddecb23132cc9641c","name": "alertname2" }], }]`
    猜你喜欢
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 2016-06-29
    • 1970-01-01
    • 2020-09-02
    • 2018-06-01
    • 2016-12-12
    相关资源
    最近更新 更多