如何使用Mongoose在MongoDB中插入JSON数组

时间:2018-08-03 13:44:19

标签: node.js mongodb rest mongoose mongoose-schema

我正在尝试使用Mongoose将数据从nodejs插入mongodb。插入数据的猫鼬模式如图所示

const NoteSchema = mongoose.Schema({
    active: String,
    institution_name:String,
    recommended_for:String,
    Medicine:[{
        medicine_name:String,
        grade_of_evidence:String,
        grade_of_recommendation:String
    }],
        free_text_recommendation:[{
        title:String,
        comment:String
    }]


},
{
    timestamps:true
});

我创建了一个单独的控制器文件来处理CRUD操作。以下代码用于 POST

const Note = require("../models/note.model");
exports.create = (req,res)=>{
const note = new Note({
    active: req.body.active || "Unititled Note",
    institution_name:req.body.institution_name,
    recommended_for:req.body.recommended_for,
    Medicine:[{
        medicine_name:req.body.Medicine.medicine_name,
        grade_of_evidence:req.body.Medicine.grade_of_evidence,
        grade_of_recommendation:req.body.Medicine.grade_of_recommendation
        }],
    free_text_recommendation:[{
        title:req.body.free_text_recommendation.title,
        comment:req.body.free_text_recommendation.comment
    }]
});
note.save().then(
    data=>{
        res.send(data);

    }).catch(err=>{
        res.status(500).send({
            message: err.message || "Some error occured while creating note"
        });
    });

};

我使用Google Chrome REST Client根据猫鼬中定义的架构插入了一些模拟数据。不会插入医学 free_text_recommendation 的对象列表,仅插入这2个对象的ID,如下所示。

enter image description here

可以成功输入所有其他数据,例如“ active”,“ institution_name”,我仅在json列表中遇到麻烦。

1 个答案:

答案 0 :(得分:0)

在为子文档建模时需要定义new mongoose.Schema。 使用此模型,它将为您服务。

const MedicineArr = new mongoose.Schema({
 medicine_name:String,
        grade_of_evidence:String,
        grade_of_recommendation:String
})

const free_text_recommendationArr = new mongoose.Schema({
            title:String,
        comment:String

})

const NoteSchema = mongoose.Schema({
    active: String,
    institution_name:String,
    recommended_for:String,
    Medicine: [MedicineArr],
    free_text_recommendation: [free_text_recommendationArr]
},
{
    timestamps:true
});