Reputation: 51
when i want to insert a document in my mongodb with monk wich has an array element of subdocuments, the funcion insert it wrong in the db. I'm calling the insert function this way:
var OrderItem = [];
OrderItem[0] = {
'model': asd1,
'size' : M,
'color' : Black
};
OrderItem[1] = {
'model': bsa2,
'size' : S,
'color' : Black
};
var newOrdenCompra = {
'fechaCompra' : d,
'items' : OrderItem
};
$.ajax({
type: 'POST',
data: newOrdenCompra,
url: '/order/addordercompra',
dataType: 'JSON'
}).done(function( response )
{
if (response.msg !== '') {
alert('Error: ' + response.msg);
}
});
and then:
/*
* POST to add orden de compra.
*/
router.post('/addordercompra', function(req, res) {
var db = req.db;
var collection = db.get('ordercompra');
collection.insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
But what i get into the BD is something like this (the example that i wrote above have less atributes in the item subdocuments):
> db.ordercompra.find().pretty()
{
"_id" : ObjectId("5601b2181430470c1266d415"),
"fechaCompra" : "2015-09-22T16:54:59Z",
"items[0][model]" : "CLUB DE LA PELEA",
"items[0][size]" : "XXXS",
"items[0][color]" : "CHOCOLATE",
"items[0][sena]" : "1200",
"items[0][precio]" : "2600",
"items[0][ordOT]" : "2",
"items[0][id]" : "55f9e402ebfcd9b414339f8f",
"items[1][model]" : "302",
"items[1][size]" : "M",
"items[1][color]" : "NEGRO",
"items[1][sena]" : "0",
"items[1][precio]" : "2100",
"items[1][ordOT]" : "",
"items[1][id]" : "55e76c0d497c742019bbb5f3"
}
>
What can i do to get the structure of an element with an array of subdocuments? am i doing it wrong or is the insert what's failing?
Thanks for the help! and sorry for my bad english. Nicolas.
Upvotes: 3
Views: 723
Reputation: 51
I've solved the problem sending the data transformed with JSON.stringify and changed the ajax parameters to dataType : 'text' and adding contentType: 'application/json'. Doing that the insert works perfect. Thanks for the help! Example Imgs:
And the BD looks like this:
Upvotes: 2