如何将多个 JSON 对象插入到模式的一个属性中? [英] how to insert multiple JSON objects to one property of a schema?

查看:73
本文介绍了如何将多个 JSON 对象插入到模式的一个属性中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在架构属性中存储多个 JSON 对象.拿这个例子...

I have a requirement to store multiple JSON objects in a property of schema. take this example...

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

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

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

I need to insert attendance of individual student which looks like this..

       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 数据库.当用户从前端提交数据时,日期和状态就会出现.所以我很难写我的帖子请求.欢迎任何类型的评论/建议/模型结构的更改.谢谢.

I am using NodeJs as Backend, EJS template as front end and mongodb database. Date and Status comes when user submits data from front end. So I am having hard time writing my post request. Any types of comments / suggestions / change of model structure are welcome. Thank you.

推荐答案

您可以创建单独的考勤模式.

You can create a separate attendance Schema.

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

const AttendanceSchema = new Schema({ 
                             date: Date,
                             status: String
                         });

const StudentSchema = new Schema({
    student_id: String,
    name:String
    attendance:[AttendanceSchema]
});

const Student = mongoose.model('Student', StudentSchema);

添加一个新学生.

let newStudent = new Student({
        student_id: student_001,
        name:'Joe'
});
newStudent.save();

更新出席情况:

let att1 =  { 
               date: 24-10-2018,
               status: 'Present'
           };

// Here 'id' is id of particular student.
Student.update({ _id: id }, { $push: { attendance: att1 } })
    .then(() => console.log("Success"))
    .catch(err => console.log(err));

稍后:

let att2 =   { 
                  date: 25-10-2018,
                  status: 'Absent'
             };

// Here 'id' is id of particular student.
Student.update({ _id: id }, { $push: { attendance: att2 } })
    .then(() => console.log("Success"))
    .catch(err => console.log(err));

这篇关于如何将多个 JSON 对象插入到模式的一个属性中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆