1

I would like to 'find' the following item, based on its 'guess.body':

{
        
        "guess": [
           
            {
                "body": "findme",
            }
        ],
        "_id": "608ee73b18a16e39e809203f"
}

This item is located in a collection called "ask", with the following model:

const askSchema = new Schema ({
guess: [{type:Schema.Types.ObjectId, ref:'guess'}],

})

In order to do this, I've tried 2 queries:

  • The first one:

     const askByGuess = await ask.find().populate("guess").find({"guess.body":"findme"})
     res.status(200).json(askByGuess)
    

which return an empty arrary

  • the second one (based on this answer: Find after populate mongoose)

     const askByGuess = await ask.find().populate({path:"guess", match{body:"findme"}}).exec(function(err, ask) {ask = ask.filter(function(ask) {return ask.guess})})
     res.status(200).json(askByGuess)
    

which returns "1".

Could someone indicate to me what I'm doing wrong?

Thank you!

KaptainIglo
  • 152
  • 1
  • 10

2 Answers2

2

I tend to agree with the solution presented in Find after populate mongoose, however, if for your specific use case you could get by a simple aggregation pipeline:

$unwind: to populate the guess field.
$lookup: performs a left outer join.
$match: to finally match your search term.

db.ask.aggregate({
  $unwind: "$guess"
},
{
  $lookup: {
    from: "guess",
    localField: "guess",
    foreignField: "_id",
    as: "guess"
  }
},
{
  $match: {
    "guess.body": "test"
  }
})

Here's a working snippet: https://mongoplayground.net/p/bJgC4rSvb_9

Jorge Paul
  • 36
  • 3
0

You don't have to use populate since the guess property is not reference to another Collection. Try this:

const askByGuess = await ask.find({
  guess: {
    $elemMatch: {
      body: "findme"
    }
  }
})
res.status(200).json(askByGuess)

Here is the working snippet: https://mongoplayground.net/p/isBMZ3Fa8QB

NeNaD
  • 18,172
  • 8
  • 47
  • 89
  • Thanks for your help. Unfortuantely, populate IS necessary, as guess does refer to another collection. Here is the model FYI. const askSchema = new Schema ({ alert: {type: Boolean, default: false, required: false}, guess: [{type:Schema.Types.ObjectId, ref:'guess'}] }) Sorry for not specifying it in my first message. – KaptainIglo May 03 '21 at 05:19