0

I'm new in mongoose and I'm trying to find user by code [user.test.test1.code] , any idea ?

Model :

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

Data :

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

query :

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

-- Solution --

Thanks you guys, both answers is work for me

2 Answers 2

1

Is as simple as do "test.test1.code": 418816 into find query like this:

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

This query will give you all documents where exists test.test1.code with value 418816.

Note that this query return the whole document, not only the sub-document into the array. But I'm assuming by your post that a user is the document where exists the field name.

Example here

Sign up to request clarification or add additional context in comments.

Comments

0

you can use $elemMatch, check the documentation

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.