简体   繁体   中英

Object spread inside of new array

I have a Node.js program that is using Mongo Atlas search indexes and is utilizing the Aggregate function inside of the MongoDB driver. In order to search, the user would pass the search queries inside of the query parameters of the URL. That being said, I am trying to build a search object based on if a query parameter exists or not. In order to build the search object I am currently using object spread syntax and parameter short-circuiting, like so:

const mustObj = {
  ...(query.term && {
    text: {
      query: query.term,
      path: ['name', 'description', 'specs'],
      fuzzy: {
        maxEdits: 2.0,
      },
    },
  })
}

This is a shortened version, as there are many more parameters, but you get the jest.

In a MongoDB search query, if you have multiple parameters that must meet a certain criteria, they have to be included inside of an array called must, like so:

{
  $search: {
    compound: {
       must: [],
    },
  },
}

So, in order to include my search params I must first turn my mustObj into an array of objects using Object.keys and mapping them to an array, then assigning the searches 'must' array to the array I've created, like so:

const mustArr = Object.keys(mustObj).map((key) => {
  return { [key === 'text2' ? 'text' : key]: mustObj[key] };
});
searchObj[0].$search.compound.must = mustArr;

What I would like to do is, instead of creating the mustObj and then looping over the entire thing to create an array, is to just create the array using the spread syntax and short-curcuiting method I used when creating the object.

I've tried the below code, but to no avail. I get the 'object is not iterable' error:

const mustArr = [
  ...(query.term && {
    text: {
      query: query.term,
      path: ['name', 'description', 'specs'],
      fuzzy: {
        maxEdits: 2.0,
      },
    },
  })
]

In all, my question is, is what I'm asking even possible? And if so, how?

Corrected based on @VLAZ comment:

while spread with array [...(item)] , item has to be array (iterable).

When you use short-circuit, the item as below,

 true && [] ==> will be `[]` ==> it will work 
 false && [] ==> will be `false` ==> wont work (because false is not array)

try some thing like (Similar to @Chau's suggestion)

const mustArr = [
  ...(query.term ? [{
    text: {
      query: query.term,
      path: ['name', 'description', 'specs'],
      fuzzy: {
        maxEdits: 2.0,
      },
    },
  }] : [])
]

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