首页 > 解决方案 > 如何将多个 JSON 对象插入到模式的一个属性中?

问题描述

我需要将多个 JSON 对象存储在模式的属性中。举个例子……

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

     const Student= Schema({
        student_id: String,
        name:String
        attendance:[
                  { 
                 date: Date,
                 Status: String
                   }
                ]
        });

我需要插入看起来像这样的个别学生的出勤率..

       student_id: student_001,
        name:'Joe'
        attendance:[
                     { 
                      date: 24-10-2018,
                      status: 'Present'
                     },
                     { 
                      date: 25-10-2018,
                      status: 'Absent'
                     },
                  //list goes on
                   ]

我使用 NodeJs 作为后端,EJS 模板作为前端和 mongodb 数据库。当用户从前端提交数据时,会出现日期和状态。所以我很难写我的帖子请求。欢迎任何类型的意见/建议/更改模型结构。谢谢你。

标签: node.jsmongodbmongoosemongoose-schema

解决方案


我建议你改变模型结构来规范化。这将改善您在未来统计信息查询中的体验。

另外,还有一个建议 - 不要在 mongoDB 中使用字符串标识符,这可能会导致在保持其唯一性方面令人头疼。Mongo 自动_id为每个文档分配属性,如果您需要识别任何对象,可以使用它。

考虑到我的建议 - 代码将如下所示:

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

const Student = Schema({
    name: String
});

const Attendance = Schema({
    date: Date,
    status: String,
    student_id: {
        type: Schema.Types.ObjectId,
        ref: 'Student'
    }
})

然后,您可以简单地创建分配给学生的出勤记录:

const attendance = new AttendanceModel({
    date: new Date('05/20/2018'),
    status: "present",
    student_id: "somestudentid"
});

推荐阅读