JuJoDi
JuJoDi

Reputation: 14955

Mongoose find all documents with a given ObjectId

I have a photo model and every photo has a vehicle associated with it:

var ObjectId = mongoose.Schema.ObjectId;
var photoSchema = mongoose.Schema({
    name: { type: String},
    path: { type: String},
    vehicle: { type: ObjectId, ref: 'Vehicle' }
  });

What query can I perform to return all photos that match a given vehicle _id? I think the query looks the same as a normal find, but I'm not sure how to turn an _id into an ObjectId.

Upvotes: 1

Views: 1789

Answers (1)

sir4ju1
sir4ju1

Reputation: 543

You don't need to turn anything, your ObjectId itself is _id but in string format when you send it through JSON to somewhere. Try following:

Photo.find({vehicle: id}, function(err, result){...});

Above id is just your vehicle's ObjectId obtained from any source e.g. User Interface

Upvotes: 2

Related Questions