简体   繁体   中英

Declaring a property in a Javascript object that ISN'T a string

I'm trying to build a javascript object to be passed along to MongoDB . This database uses an operator $or which lets you search for multiple keys in a property at once.

Because of this, the $or operator cannot be in quotation marks, because it is actually an operator in the lookup function.

For reference, the lookup function looks like this:

db.inventory.find( { price:1.99, $or: [ { qty: { $lt: 20 } }, { sale: true } ] } )

I have found a way to 'build' an $or property out of some variables, but for some reason the property name keeps being treated as though it's a string. Here's my code:

    var criteria = { $or: []};

    properties.forEach(function(property) {
        var propParts = property.split('=');
            if(!(propParts[1].indexOf('&') === -1)){
                var value = propParts[1].match(/[-'"\w\s]+/g);
                    for (var i = 0; i<value.length; i++){
                        var tempObj = {};
                        tempObj[propParts[0]] = value[i];
                        criteria.$or.push(tempObj);
                    }
            }else{       
            criteria[propParts[0]] = new RegExp(propParts[1], "i");
        }
    });

if(criteria.$or.length<=0){
    delete criteria.$or;
}
console.log(criteria);

In my console, this is being output as:

{ '$or': [ { designer: 'abc' }, { designer: 'def' } ] }

I am using similar code elsewhere (with $push instead of $or ) and it works just fine, I'm declaring it in exactly the same way.

Is it possible to ensure that the property isn't being treated as a string? How can I achieve this here?

Javascript object keys are always coerced to strings. That you can specify some keys without quotes in object literals {key: 0} or using dot notation object.key = 0 is merely syntactic sugar for keys that also happen match the production for identifiers. '$or' is a valid javascript identifier, so you can say either:

{$or: [...]}

or

{"$or": [...]}

or

{'$or': [...]}

and they're all equivalent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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