Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

mongodb - How to perform a search on selected fields in mongoose

Say I have User schema with three fields, a username, email, and password, how would I do a query with mongoose in which I search the username and email fields only and return matched documents.

For example in expressjs the URL would be:

http://localhost:8000/users/search?q=testuser

Posting to that ur should return an array of documents that have testuser either in its email, username, or both.

question from:https://stackoverflow.com/questions/65852440/how-to-perform-a-search-on-selected-fields-in-mongoose

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is as simple as pass the values into find() method with an $or condition.

Check this example:

db.collection.find({
  "$or": [
    {
      "username": {
        "$regex": "testuser"
      }
    },
    {
      "email": {
        "$regex": "testuser"
      }
    }
  ]
})

Return the values where username or email contains testuser.

With mongoose you can use the saeme:

yourModel.find({
            "$or": [
               { "username": { "$regex":"testuser" } },
               {"email": { "$regex":"testuser" } }
             ]
        }).then(result => {
            console.log(result);
        }).catch(e => {
            console.log(e);
        })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...