0

I have this piece of code :

db.collection('coders', function(err, collection) {
        collection.find(toFind).toArray(function(err, items) {
            res.send(items);
        });

where toFind is something like {"position":2,"$or":[{"position":{"$lt":20}},{"name":"whatever"}]} It is a String, so the previous code doesn't execute, because it needs an object. I already know, that I can create object from String like

var obj={}
obj[key] = {value}

But how can I create an object without key ?

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
slezadav
  • 6,104
  • 7
  • 40
  • 61

2 Answers2

1

To convert toFind from a string into an object that you can pass into find, use JSON.parse:

toFind = JSON.parse(toFind);
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
0

Everything in JavaScript is an object. However, what you apparently want is a simple variable:

obj[key] = value;

The object you posted above would be defined exactly like this:

var obj = {
    "position": 2,
    "$or": [{
        "position": {
            "$lt": 20
        }
    }, {
        "name": "whatever"
    }]
};
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 1
    No, you also have primitive types, like boolean, string, number, etc. – Marcel Korpel Mar 01 '13 at 13:00
  • 1
    Ah well, that's more of an internal thing though. For example, even a plain `number` has the methods from `Number.prototype` – ThiefMaster Mar 01 '13 at 13:02
  • [(Not) Everything in JavaScript is an Object](http://blog.brew.com.hk/not-everything-in-javascript-is-an-object/). Numbers are primitives, when you try to access a property from it, JavaScript autoboxes the primitive and accesses that object wrapper's property. See my answer at http://stackoverflow.com/a/44042894/3966682 – d4nyll May 18 '17 at 09:05