javascript - How can I save an empty array into mongodb using js - Stack Overflow

Basically I got my app up an running but I'm stuck with a problem: if I pass an object that contai

Basically I got my app up an running but I'm stuck with a problem: if I pass an object that contains an empty array to be saved, the array is not saved into the db. I'm not sure this is a problem in js or the mongo driver, but in order to save the empty array I need to pass the array like so: products: [''].

This is the structure of my mongo document:

_id: ObjectId(...),
name: 'String',
subcategories: [
    {
        subcategory: 'string',
        products: [
            {
                 name: 'string'
                 price: integer
            }
        ]
    }
]

So in my front-end I'm grabbing the whole document through an ajax call pushing a new object into the subcategories array. The new object looks like this:

{subcategory:'string', products:['']}

And this works okay until I need to insert a new object inside the array: Because I've grabbed the whole object, pushed the new object to the array, the previous one looks like this:

{subcategory: 'string'}

Having lost the mention to products:[] array in the process.

How can I get around this? I need to be able to have empty arrays in my object.

EDIT

What I did on front end: Got the whole object with $.get which returned:

var obj = 
_id: ObjectId(...),
name: 'String',
subcategories: [
    {
        subcategory: 'Subcategory1',
        products: [
            {
                 name: 'string'
                 price: integer
            }
        ]
    }
];

Then on the front end I've pushed the new object category inside the subcategories array:

data.subcategories.push({subcategory: 'Subcategory2', products: ['']})

Where subcat was a string with the category name. On my db I could see that I've successfully added the object:

var obj = 
_id: ObjectId(...),
name: 'String',
subcategories: [
    {
        subcategory: 'Subcategory1',
        products: [
            {
                 name: 'string'
                 price: integer
            }
        ]
    },
    {
         subcategory: 'Subcategory2'
         products: []
    }
];

The problem was when I wanted to add another subcategory, the previous one return empty:

var obj = 
_id: ObjectId(...),
name: 'String',
subcategories: [
    {
        subcategory: 'Subcategory1',
        products: [
            {
                 name: 'string'
                 price: integer
            }
        ]
    },
    {
         subcategory: 'Subcategory2'
    },
    {
         subcategory: 'Subcategory3'
         products: []
    },
];

Because at some point the empty array was removed from the object. Like I said, I did fix this in the front end, so the error jade was throwing has been addressed, but I still find odd that the products: [] was being removed from the document.

I'm new to MongoDb and node, not to mention that I'm also new with JS, so it might well be a feature that I'm unaware of.

Basically I got my app up an running but I'm stuck with a problem: if I pass an object that contains an empty array to be saved, the array is not saved into the db. I'm not sure this is a problem in js or the mongo driver, but in order to save the empty array I need to pass the array like so: products: [''].

This is the structure of my mongo document:

_id: ObjectId(...),
name: 'String',
subcategories: [
    {
        subcategory: 'string',
        products: [
            {
                 name: 'string'
                 price: integer
            }
        ]
    }
]

So in my front-end I'm grabbing the whole document through an ajax call pushing a new object into the subcategories array. The new object looks like this:

{subcategory:'string', products:['']}

And this works okay until I need to insert a new object inside the array: Because I've grabbed the whole object, pushed the new object to the array, the previous one looks like this:

{subcategory: 'string'}

Having lost the mention to products:[] array in the process.

How can I get around this? I need to be able to have empty arrays in my object.

EDIT

What I did on front end: Got the whole object with $.get which returned:

var obj = 
_id: ObjectId(...),
name: 'String',
subcategories: [
    {
        subcategory: 'Subcategory1',
        products: [
            {
                 name: 'string'
                 price: integer
            }
        ]
    }
];

Then on the front end I've pushed the new object category inside the subcategories array:

data.subcategories.push({subcategory: 'Subcategory2', products: ['']})

Where subcat was a string with the category name. On my db I could see that I've successfully added the object:

var obj = 
_id: ObjectId(...),
name: 'String',
subcategories: [
    {
        subcategory: 'Subcategory1',
        products: [
            {
                 name: 'string'
                 price: integer
            }
        ]
    },
    {
         subcategory: 'Subcategory2'
         products: []
    }
];

The problem was when I wanted to add another subcategory, the previous one return empty:

var obj = 
_id: ObjectId(...),
name: 'String',
subcategories: [
    {
        subcategory: 'Subcategory1',
        products: [
            {
                 name: 'string'
                 price: integer
            }
        ]
    },
    {
         subcategory: 'Subcategory2'
    },
    {
         subcategory: 'Subcategory3'
         products: []
    },
];

Because at some point the empty array was removed from the object. Like I said, I did fix this in the front end, so the error jade was throwing has been addressed, but I still find odd that the products: [] was being removed from the document.

I'm new to MongoDb and node, not to mention that I'm also new with JS, so it might well be a feature that I'm unaware of.

Share Improve this question edited Jun 17, 2014 at 13:55 BenMorel 36.7k52 gold badges206 silver badges337 bronze badges asked Nov 17, 2013 at 14:48 WagnerMatosUKWagnerMatosUK 4,4399 gold badges59 silver badges100 bronze badges 7
  • Could you explain why you need to do this? MongoDB intentionally doesn't save "empty" data (which an empty array would be). I'd suggest that the client code in NodeJS should provide a default value. – WiredPrairie Commented Nov 17, 2013 at 15:10
  • 3 empty array is NOT empty data. there is a big difference between products: null or products: not existing and products: [ ] - for one it's a different BSON type. It's possible there is a bug - OP, it's not 100% clear to me what your code is doing. When you say you "grabbed the whole object" which object are you referring to? – Asya Kamsky Commented Nov 17, 2013 at 19:56
  • Can you give exact code you use to update the document? Sounds like you may not be using update() with $push but pushing locally in the client code? also, what version of the driver are you using and what version of MongoDB? – Asya Kamsky Commented Nov 17, 2013 at 19:57
  • Ok, first things first: I was getting an error on the front end as Jade couldn't loop through an undefined object (if the array was not saved category.subcategories was retuning as undefined). I fixed with an conditional in the front end so the error is gone. @AsyaKamsky What I did in the from end was grab the whole object as described above then pushed the changes into the array. – WagnerMatosUK Commented Nov 17, 2013 at 20:20
  • You are saying that when you save({_id:1, foo:[{bar:'x',arr:[]}]}) wha t ends up saved in the db is {_id:1, foo:[{bar:'x'}]} is that right? and that's reproducible? – Asya Kamsky Commented Nov 17, 2013 at 20:26
 |  Show 2 more ments

2 Answers 2

Reset to default 0

When passing empty arrays to Mongo they are interpreted as empty documents, {}. Zend Json encoder will interpret them as empty arrays []. I understand that it's not possible to tell which one is correct. Incase of empty arrays try posting as

Array[null]; instead of Array[];

This will be working fine

When passing empty arrays to Mongo they are interpreted as empty documents, {}. Zend Json encoder will interpret them as empty arrays []. I understand that it's not possible to tell which one is correct.

In my view it's more logical that the actual php array (when empty) is interpreted as an array in MongoDB. Although that will require something else to identify empty documents it's still more logical than the current behaviour.

A possible solution would be to introduce a new object, MongoEmptyObject (or using the stdObj) whenever one want to introduce an empty object.

Meanwhile, a workaround is to detect empty arrays in php, and inject a null value $arr[0] = null; Then the object will be interpreted as an empty array in mongo.

The workaround works both in PHP and in the mongo console. Question: does json allow for arrays with null values? If so, then the workaround is a sign of another bug.

PHP: if (is_array($value) && empty($value))

{ $value[0] = null; } Mongo Console:

var b =

{hej:"da", arr: [null]}

db.test.save(b); db.test.find();

{"_id" : "4a4b23adde08d50628564b12" , "hej" : "da" , "arr" : []}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744370176a4570909.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信