简体   繁体   English

Node.js字符串里面有javascript对象参数

[英]Node.js string inside javascript object argument

I'm not really sure how to name this problem but essentially I am using the Mongoose package for MongoDB and the function is not behaving. 我不确定如何命名这个问题,但实际上我使用的是MongoDB的Mongoose包,而且函数没有表现。 The function in question is: 有问题的功能是:

var value = 'onetwothree'
model.findOne({ 'name': value }, callback)

which allows me to search the database for the attribute 'name' . 这允许我在数据库中搜索属性'name' However, if I try to pass 'name' in as a variable, the function doesn't work. 但是,如果我尝试将'name'作为变量传递,则该函数不起作用。 For example, this doesn't work: 例如,这不起作用:

var attribute = 'name'
model.findOne({ attribute: value}, callback)

How do I call the findOne() function while making the attribute argument variable, ie I could pass in 'name' , 'age' , 'city' , etc. 如何在创建属性参数变量时调用findOne()函数,即我可以传入'name''age''city'等。

You can just create the object before passing it into the function and assign the dynamic property using the [] notation: 您可以在将对象传递给函数之前创建对象,并使用[]表示法分配动态属性:

var query = {};
var attr = 'city';
var val = 'Miami';

// set the dynamic property
query[attr] = val; // { city: 'Miami' }

model.findOne(query, callback)

Or in ES6 (if you're using Babel) you can do it directly with a Computed Property Name: 或者在ES6中(如果您使用的是Babel),您可以使用计算属性名称直接执行此操作:

const attr = 'city';
const val = 'Miami';
const query = { [attr]: val }; // { city: 'Miami' }

model.findOne(query, callback);

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

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