簡體   English   中英

Object 分布在新陣列內部

[英]Object spread inside of new array

我有一個 Node.js 程序,它使用 Mongo Atlas 搜索索引,並在 MongoDB 驅動程序內使用聚合 function。 為了進行搜索,用戶將在 URL 的查詢參數中傳遞搜索查詢。 話雖如此,我正在嘗試根據查詢參數是否存在來構建搜索 object。 為了構建搜索 object 我目前正在使用 object 擴展語法和參數短路,如下所示:

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

這是一個縮短的版本,因為有更多的參數,但你會開玩笑。

在 MongoDB 搜索查詢中,如果您有多個必須滿足特定條件的參數,則它們必須包含在名為 must 的數組中,如下所示:

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

因此,為了包含我的搜索參數,我必須首先使用Object.keys將我的mustObj轉換為一個對象數組並將它們映射到一個數組,然后將搜索“必須”數組分配給我創建的數組,如下所示:

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

我想要做的是,而不是創建mustObj然后循環整個事物以創建一個數組,而是使用我在創建 object 時使用的擴展語法和短程序方法來創建數組。

我已經嘗試了以下代碼,但無濟於事。 我收到“對象不可迭代”錯誤:

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

總而言之,我的問題是,我要問的甚至可能嗎? 如果是這樣,怎么辦?

根據@VLAZ 評論更正:

雖然使用數組[...(item)] spread ,但item必須是數組(可迭代)。

當您使用短路時, item如下,

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

嘗試一些事情(類似於@Chau的建議)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM