node.js - 如何将多个 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 数据库。当用户从前端提交数据时,会出现日期和状态。所以我很难写我的帖子请求。欢迎任何类型的意见/建议/更改模型结构。谢谢你。
解决方案
我建议你改变模型结构来规范化。这将改善您在未来统计信息查询中的体验。
另外,还有一个建议 - 不要在 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"
});
推荐阅读
- r - 将混合类型折叠成一个整洁的逗号分隔字符串
- amazon-s3 - 尝试访问重新加载或刷新或在角度 5 的新选项卡中访问时收到 AccessDenied
- javascript - 简单的正则表达式使 android 崩溃,在 iOS 中运行良好
- jquery - 如何在不使用 class 或 id 的情况下选择 2nd h2?jQuery
- powershell - AzureSQL 多次调用-SQLCmd 循环和连接错误
- textures - MonoGame 添加纹理
- javascript - React.createRef() 导致错误“预期 ref 是函数或字符串”
- windows - 使用手动分配的控制台在 CMD.EXE 中输出混乱
- c# - 将多个会话添加到一个中(以获得许可)
- javascript - 重置我用作计数器的全局变量