[英]How to insert an array of JSON in MongoDB using Mongoose
I am trying to insert data from nodejs to mongodb using Mongoose. 我试图使用Mongoose将数据从nodejs插入到mongodb中。 The Mongoose schema for inserting data is as shown 插入数据的Mongoose模式如下所示
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
});
I have created a separate controller file to handle CRUD operations. 我创建了一个单独的控制器文件来处理CRUD操作。 The code below is for POST 以下代码用于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"
});
});
};
I used the Google Chrome REST Client to insert some mock data according to the schema defined in mongoose. 我使用Google Chrome REST Client根据猫鼬中定义的架构插入了一些模拟数据。 The list of objects for Medicine and free_text_recommendation does not get inserted, only the id for those 2 gets inserted as shown below. 不会插入Medicine和free_text_recommendation的对象列表,仅插入这2个对象的ID,如下所示。
enter image description here 在此处输入图片说明
All the other data such as "active","institution_name" could be successfully entered, I am having trouble only with the list of json. 可以成功输入所有其他数据,例如“ active”,“ institution_name”,我仅在json列表方面遇到麻烦。
you need to define new mongoose.Schema
when you modeling for subdocuments. 在为子文档建模时,需要定义new mongoose.Schema
。 use this model, it will work for you. 使用此模型,它将为您工作。
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.