簡體   English   中英

查詢生成器如何在填充的文檔上使用“where”子句

[英]Query builder how to use "where" clause on populated documents

我在使用 Mongoose 查詢時遇到了一些問題。 我只是想使用where子句在集合中查找文檔。

不幸的是,您似乎不能在填充文檔上使用 where 子句


這是集合模式

const schema: Schema = new Schema({
    game: { type: Schema.Types.ObjectId, ref: 'Game', required: true, index: true },
    players: [{ type: Schema.Types.ObjectId, ref: 'Player', required: true, index: true }],
    scores: [{ type: String }],
    resultDate: { type: Date}
});

我正在嘗試查找type = 1v1的所有游戲,所以我嘗試了這個

let query = Matchs.find()
    .populate('game')
    .populate('players')
    .where('game.name').equals('Trackmania')

const matchs: Match[] = await query.exec();

這將返回一個空數組。


筆記

  • 刪除 where 子句會返回正確的結果(所有匹配項)
  • 游戲中的任何 where 子句都返回一個空數組
  • 我想使用查詢生成器而不是傳遞 json ,因為我使用一些參數來定義我要查詢的內容

我讀到 where 子句不適用於嵌套文檔,但一定有辦法做到這一點嗎? 我錯過了什么嗎?

您可以使用查找和匹配而不是位置。

MatchesModel.aggregate([

const GameName =  req.query;

  {"$lookup":{
    "from":"games", // name of the foreign collection
    "localField":"game",
    "foreignField":"_id",
    "as":"game"
  }},
   {"$lookup":{
    "from":"players", 
    "localField":"players",
    "foreignField":"_id",
    "as":"players"
  }},
  {"$match":{
     "game.name":{
      "$eq": GameName
    }
  }}
])

暫無
暫無

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

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