簡體   English   中英

mongoose 在 object 的數組中找到 object

[英]mongoose find object into array of object

我是 mongoose 的新人,我正在嘗試通過代碼 [ user.test.test1.code ] 查找用戶,知道嗎?

Model:

const userSechema = new mongoose.Schema({     
name: {
    type: String,
    required: true
  },
     test: [{}],
 })

數據:

{
    "_id": {
        "$oid": "600020ab34742c2d34ae45e5"
     },
    "test": [{
       "test1": {
            "code": 11111
        },
       "test2": {
          "code": 22222
        }
      }]
   "name": "daniel"
}

詢問:

let regex = new RegExp(req.query.searchUserKey, 'i')
const users = await User.find({ $or: [{'name': regex },{'test.test1': { code : regex} }]})

- 解決方案 -

謝謝你們,兩個答案都對我有用

就像"test.test1.code": 418816像這樣查找查詢:

db.collection.find({
  "test.test1.code": 418816
})

此查詢將為您提供所有存在test.test1.code且值為418816的文檔。

請注意,此查詢返回整個文檔,而不僅僅是數組中的子文檔。 但我假設你的帖子user是存在字段name的文檔。

這里的例子

你可以使用$elemMatch ,查看文檔

const users = await User.find(
   { test: { $elemMatch: { "test1.code": 418816 } } }
)

暫無
暫無

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

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