[英]How to insert dynamic data in mongoose search query with an array of embedded documents and $elemMatch etc
我在嵌入式文檔數組上使用多個$elemMatch
查詢,類似於此處看到的內容: https://www.mongodb.com/docs/manual/tutorial/query-array-of-documents/#a-single-嵌套文檔滿足嵌套字段上的多個查詢條件
我正在為我的投資組合做一個副項目,用戶可以在其中發布電影交易(他們擁有的假電影)。 他們通過添加他們擁有的電影以及他們可能正在尋求回報的電影來創建交易。
服務端會收到客戶端發來的兩個arrays,他們正在提供的電影和正在尋找的電影。 在下面的這個mongoose
查詢中,我希望它不會太奇怪,它主要檢查數據庫中與客戶交易匹配的交易。 每次用戶刪除/添加電影時都會執行此查詢,因此根據發送的內容,我想查詢包含offering
中的任何電影的文檔(交易),並且還包括seeking
中的任何動作。
本例中的每個文件都是一個單獨的電影交易,其中包含 2 arrays 的嵌入文件, offering
和seeking
const movieTrades = await Trade.find({
$and: [
{
$or: [
{
offering: { $elemMatch: {} },
},
{
offering: { $elemMatch: { name: "lion king" } },
},
],
},
{
$or: [
{
seeking: { $elemMatch: { name: "lego movie" } },
},
{
seeking: { $elemMatch: { name: "nemo" } },
},
],
},
],
});
我的問題這在使用硬編碼數據進行測試時效果很好,但是我將如何處理如我所說的從客戶端發送的動態數據。
假設我從客戶端到服務器獲得了兩個offering
和seeking
arrays,並且 arrays 中的任何一個都可以包含 x 數量的電影對象,我將如何將這些對象插入到上述查詢的格式中?
我唯一能想到的是,當我得到類似offering
數組的東西時,我循環遍歷offering
數組並像上面那樣格式化內容,將它說成一個變量,並將該變量包含在 mongo 查詢中,如下所示:
// This will return an array filled with the movie objects, but in the format matching the above $or with the $elemMatch variables embedded
const offeringFormated = offering.map((movieObject) => {
return { offering: {$elemMatch: movieObject }}
})
const movieTrsades = await MovieTrade.find({
$and: [
{
$or: offeringFormated,
}....
],
});`
我擔心這要么是非常不正確的,要么是破壞了我不知道的mongoose
或js
的某種編碼約定。
或者,如果有人理解我的目的,我將非常感謝有關如何更有效地或遵守編程規則/標准的其他方式的指導或幫助。 謝謝!
您可以使用$in
運算符簡化查詢:
const movieTrades = await Trade.find({
offering: { $in: offering },
seeking: { $in: seeking }
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.