简体   繁体   English

在Mongo中利用ES6默认参数

[英]Taking advantage of ES6 default parameters with Mongo

I am wondering if there is a way I can construct mongo's queries to take advantage of es6 default parameters. 我想知道是否有一种方法可以构造mongo的查询以利用es6默认参数。 I have the following method. 我有以下方法。 I want to return all the data if make, model and year is not specified. 如果未指定品牌,型号和年份,我想返回所有数据。 I am trying to find an elegant solution but so far all I can think of is manual if else. 我正在尝试找到一种优雅的解决方案,但到目前为止,我能想到的只是手动操作。

getStyles({ make = '', model = '', year = '-1' }) {
        return this.db
            .collection('styles')
            .find({ 'make.niceName': make, 'model.niceName': model, 'year.year': parseInt(year) })
            .toArray();
    }

Note: This is causing some confusion. 注意:这引起一些混乱。 I am using destructing on purpose. 我故意使用破坏。 The problem is not how to write this function. 问题不在于如何编写此函数。 The problem is how to construct a mongo query so it would ignore empty values. 问题是如何构造mongo查询,以便它将忽略空值。

Assuming getStyles is your own method, sure, you can give make , model , and year defaults. 假设getStyles是您自己的方法,那么可以确定makemodelyear默认值。 You can also give a default for the whole object you're destructuring so caller doesn't have to pass anything : 您还可以为要销毁的整个对象提供默认值,这样调用方就不必传递任何内容

function getStyles({make = '', model = '', year = '-1'} = {}) {
// Overall default ------------------------------------^^^^^
    return // ...
}

The question is not how to organize/write my function but how to use es6 features to write a cleaner code that would work with mongo. 问题不是如何组织/编写我的函数,而是如何使用es6功能编写可与mongo一起使用的更简洁的代码。 IE if the user didn't pass anything I want to return all the styles but mongo actually looks for empty fields so it doesn't return anything. IE浏览器,如果用户没有传递任何内容,我想返回所有样式,但是mongo实际上会查找空字段,因此它不会返回任何内容。

It sounds to me like you don't want default parameters (except perhaps the overall default). 在我看来,您不需要默认参数(也许除了整体默认值)。 Instead, you want to automate how you build the object you pass find . 相反,您想自动化如何通过find构建对象。

Given your code example, you can readily do that with Object.keys on your object. 给定您的代码示例,您可以通过在对象上使用Object.keys轻松完成此操作。 So accept as an object, eg: 因此接受作为对象,例如:

function getStyles(options = {}) {

...an then build your find options based on options : ...然后根据options建立您的find options

const findParams = {};
Object.keys(options).forEach(key => {
  findParams[key + ".niceName"] = options[key];
});

Live example: 现场示例:

 function getStyles(options = {}) { const findParams = {}; Object.keys(options).forEach(key => { findParams[key + ".niceName"] = options[key]; }); console.log(`find options: ${JSON.stringify(findParams)}`); } let results = getStyles({make: "Ford", model: "Mustang"}); results = getStyles({make: "Ford", model: "Mustang", year: 2017}); 

If the mapping of the name you accept ( make ) to the name you need for find ( make.niceName ) isn't as easy as just appending .niceName , it's easy enough to have a Map (or just object) you build once: 如果您接受的名称( make )到find所需的名称( make.niceName )的make.niceName不像附加.niceName那样简单,那么一次构建一个Map (或对象)就足够容易了:

const paramNames = new Map([
  ["make", "make.niceName"],
  ["model", "model.niceName"],
  ["year", "year.niceName"]
]);

...and then use: ...然后使用:

const findParams = {};
Object.keys(options).forEach(key => {
  const paramName = paramNames.get(key);
  if (paramName) {
    findParams[paramName] = options[key];
  }
});

Live example: 现场示例:

 const paramNames = new Map([ ["make", "make.niceName"], ["model", "model.niceName"], ["year", "year.niceName"] ]); function getStyles(options = {}) { const findParams = {}; Object.keys(options).forEach(key => { const paramName = paramNames.get(key); if (paramName) { findParams[paramName] = options[key]; } }); console.log(`find options: ${JSON.stringify(findParams)}`); } let results = getStyles({make: "Ford", model: "Mustang"}); results = getStyles({make: "Ford", model: "Mustang", year: 2017}); 


Side note: Defaults don't have to be strings, so if you use numbers for year rather than strings, your default would just be -1 , not '-1' . 旁注:默认值不必是字符串,因此,如果您将数字用于year而不是字符串,则默认值将是-1 ,而不是'-1'

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

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