node.js - 如何使用 Mongoose 在 MongoDB 中插入 JSON 数组

标签 node.js mongodb rest mongoose mongoose-schema

我正在尝试使用 Mongoose 将数据从 nodejs 插入到 mongodb。 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
});

我创建了一个单独的 Controller 文件来处理 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 中定义的架构插入一些模拟数据。 Medicinefree_text_recommendation 的对象列表不会被插入,只会插入这两个对象的 ID,如下所示。

enter image description here

所有其他数据,例如“active”、“institution_name”都可以成功输入,我仅在 json 列表方面遇到问题。

最佳答案

在为子文档建模时,您需要定义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
});

关于node.js - 如何使用 Mongoose 在 MongoDB 中插入 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51674062/

相关文章:

javascript - 是否可以将流同步转换为缓冲区?

node.js - 清除 cloudflare 上的缓存是否也会清除浏览器上的缓存?

javascript - mongodb insert 是否创建新模式

javascript - 我正在使用react-image-crop与react和Express来使用Crop上传个人资料图片

python - $and mongodb 中的查询未返回结果

c# - Office 365 Rest API 读取 In-Reply-To 字段

java - 针对 Spring Security 的应用程序身份验证

node.js - 如何使用 AWS lambda 验证 S3 中的 zip 结构

javascript - 将 C++ 虚拟方法绑定(bind)到具有覆盖功能的 js

java - 发布/记录 Spring-REST API