Mongoose查找具有给定ObjectId的所有文档

时间:2022-09-11 19:22:33

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.

我可以执行哪些查询来返回与给定车辆_id相匹配的所有照片?我认为查询看起来与普通查找相同,但我不确定如何将_id转换为ObjectId。

1 个解决方案

#1


2  

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:

你不需要转动任何东西,你的ObjectId本身是_id,但是当你通过JSON发送到某个地方时它是字符串格式的。试试以下:

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

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

以上id只是从任何来源获得的车辆的ObjectId,例如用户界面

#1


2  

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:

你不需要转动任何东西,你的ObjectId本身是_id,但是当你通过JSON发送到某个地方时它是字符串格式的。试试以下:

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

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

以上id只是从任何来源获得的车辆的ObjectId,例如用户界面