简体   繁体   English

在Javascript对象中声明一个不是字符串的属性

[英]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 . 我正在尝试构建一个javascript对象以传递给MongoDB This database uses an operator $or which lets you search for multiple keys in a property at once. 此数据库使用运算符$or允许您一次搜索属性中的多个键。

Because of this, the $or operator cannot be in quotation marks, because it is actually an operator in the lookup function. 因此, $or运算符不能使用引号,因为它实际上是查找函数中的运算符。

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. 我找到了一种从某些变量中“构建” $or属性的方法,但由于某种原因,属性名称一直被视为字符串。 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. 我在其他地方使用类似的代码(使用$push代替$or )并且它工作正常,我以完全相同的方式声明它。

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. Javascript对象键始终强制为字符串。 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. 你可以在对象文字{key: 0}指定一些没有引号的{key: 0}或者使用点符号object.key = 0这只是键的语法糖,它也会发生与标识符的生成相匹配。 '$or' is a valid javascript identifier, so you can say either: '$或'是有效的JavaScript标识符,因此您可以说:

{$or: [...]}

or 要么

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

or 要么

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

and they're all equivalent. 而且他们都是等同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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