【发布时间】:2019-01-11 10:22:04
【问题描述】:
我正在尝试使用 Mongoose 将数据从 nodejs 插入到 mongodb。插入数据的Mongoose schema如图所示
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 客户端根据 mongoose 中定义的模式插入了一些模拟数据。 Medicine 和 free_text_recommendation 的对象列表没有被插入,只有这两个的 id 被插入,如下所示。
“active”、“institution_name”等所有其他数据都可以成功输入,我只有json列表有问题。
【问题讨论】:
标签: node.js mongodb rest mongoose mongoose-schema