繁体   English   中英

使用nodejs在mongodb中插入嵌入式文档

[英]insert embedded document in mongodb using nodejs

我正在尝试通过nodejs在MongoDB中插入嵌入式文档。 这是嵌入式文档的架构

var patientSchema = new mongoose.Schema({
    status: {type: String},
    message:{type: String},
    statusCode:{type: Number},
    user: [{
        pname: {type : String },
        email: {type : String },
        password: {type : String },
        mobile: {type : String},
        otp:{type: Number},
        age: {type : String }
    }]
})

这是插入代码

router.post('/panel/register', function(req, res){
        console.log(req.body.mobile_number+req.body.email);
        new patient({
            status: "ok",
            message:"success",
            statusCode:"201",
            'user.$.pname': req.body.name,
            'user.$.password': req.body.password,
            'user.$.email': req.body.email,
            'user.$.mobile': req.body.mobile_number
        }).save(function(err, doc){
            if(err) res.json(err);
            else {
                    res.json({"doc ":doc});
            }
        })
    })

但是每当我尝试使用此代码插入数据时,都会向我显示此错误

{
    "code": 11000,
    "index": 0,
    "errmsg": "E11000 duplicate key error index: rhc.patients.$mobile_1 dup key: { : null }",
    "op": {
        "status": "ok",
        "message": "success",
        "statusCode": 201,
        "_id": "59f38e4d94fff613fc8c4979",
        "user": [],
        "__v": 0
    }
}

据我了解,此错误是因为这没有映射用户内部移动电子邮件的值,有人可以帮助解决它,我认为我以错误的方式插入了它,请帮助

编辑:

为了清楚起见:问题实际上不是语法,而是在不更新数据库的情况下删除的唯一约束。 您可以在这里这里阅读有关内容的更多信息。

原始答案:

您可以这样做:

router.post('/panel/register', function(req, res){
        console.log(req.body.mobile_number+req.body.email);
        new patient({
            status: "ok",
            message:"success",
            statusCode:"201",
            user: [{
                pname: req.body.name,
                password: req.body.password,
                email: req.body.email,
                mobile: req.body.mobile_number
            }]
        }).save(function(err, doc){
            if(err) res.json(err);
            else {
                    res.json({"doc ":doc});
            }
        })
    })

这将在用户数组中创建一个用户对象。 您确定它不仅应该是对象上的数组吗? 从模型和控制器中都删除[],以使其成为普通对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM