【问题标题】:How to insert an array of JSON in MongoDB using Mongoose如何使用 Mongoose 在 MongoDB 中插入 JSON 数组
【发布时间】: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 中定义的模式插入了一些模拟数据。 Medicinefree_text_recommendation 的对象列表没有被插入,只有这两个的 id 被插入,如下所示。

enter image description here

“active”、“institution_name”等所有其他数据都可以成功输入,我只有json列表有问题。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 这种情况下如何形成请求体?
    猜你喜欢
    • 2015-09-20
    • 2021-10-04
    • 2021-11-25
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 2015-08-22
    • 2018-06-16
    • 2016-09-19
    相关资源
    最近更新 更多