Reputation: 1111
I am trying to insert embedded document in MongoDB through nodejs. This is schema of embedded document
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 }
}]
})
and here is the code of insertion
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});
}
})
})
but whenever i am trying to insert data using this code it is showing me this error
{
"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
}
}
As i am understanding this error is because this is not mapping the values of email, mobile inside the user, can someone help to resolve it, i think i am inserting it in wrong way , please help
Upvotes: 1
Views: 2043
Reputation: 18939
Edit:
For clarity: the problem wasn't really the syntax, but rather a unique constraint that was removed, without the database being updated. You can read more about that here and here.
Original answer:
You can do it like this:
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});
}
})
})
This will create a user object in the user array. Are you sure it's supposed to be an array on not just an object? Remove [] from both the model and controller to make it an ordinary object.
Upvotes: 2