Search code examples
mongoose

mongooseJS find docs with IDs in an array


I need to pull back documents that have ID stored in an array of ObjectIds so I have an "id" (123) and I want all the DOcs where the "tenants" have an array element of (123)

Data looks like this

{
  "_id": ObjectId("abc"),
  "name": "Miroslav",
  "tenants": [
    ObjectId("123"),
    ObjectId("456")
  ]
}

{
  "_id": ObjectId("abd"),
  "name": "Lothar",
  "tenants": [
    ObjectId("123"),
    ObjectId("694")
  ]
}

of course the mongoDB systax

things.find( { 'tenants': ObjectId(123) } )

works just fine.

Mongoose complains

ReferenceError: ObjectId is not defined

So I tried this

things.find( { 'tenants': mongoose.Schema.ObjectId(123) } )

And in a bazaar twist, mongoose returned ALL records EXCEPT the 2 expected.

I've seen this question posted 3 years ago, and that post didn't have an answer, hopefully someone here will have a solution.

Im using "mongoose": "4.9.8" (due to a specific 'promise' issue I cannot go up a version, at the moment)

thx


Solution

  • to convert to ObjectId you need to use:

    things.find({tennants: mongoose.Types.ObjectId("123")});
    

    the difference between mongoose.Schema.ObjectId and mongoose.Types.ObjectId is that the latter is the ObjectId constructor function. it can even be used like:

    var id = new mongoose.Types.ObjectId("123");
    

    to create an objectId and store it in the id variable.

    while mongoose.Schema.ObjectId (or mongoose.Schema.Types.ObjectId) refers to a data type. that's what you'd use in your schema. the same way you might set

    name: String
    

    in a schema, you use mongoose.Schema.Types.ObjectId to specify that the data type is a mongoose ObjectId.

    note: I remember reading this in the docs a few months ago, but i was unable to find the docs now, i think my explanation is fairly adequate though