Reputation: 113
i have two schemas, one Schema is and order's schema and the other Schema is the establishment Schema..
Order Schema:
const orderSchema = new Schema({
buyer: {type:Schema.Types.ObjectId,ref: "User"},
seller: {type:Schema.Types.ObjectId,ref: "Establishment"},
amount: {type: Number},
tax: {type: Number},
returned_products: [
{
product:{type:Schema.Types.ObjectId,ref: "Product"},
quantity:{type: Number},
status:{type:String,default:"pending"}
}
],
products:[
{
product:{type:Schema.Types.ObjectId,ref: "Product"},
quantity:{type: Number},
_id:false
}
],
created_at:{type: Date,default: new Date()},
updated_at:{type: Date,default: new Date()}
})
Establishent Schema:
const establishmentSchema = new Schema({
name: { type: String, required: true },
address: { type: String, required: true },
location: {
type: { type: String },
coordinates: [Number]
},
email:{type:String,required:true},
phone:{type:String, required:true},
photo_url:{type: String},
schedule:{type: Array, required:true},
supervisors:[
{type:Schema.Types.ObjectId,ref: "User"}
],
company:{type:Schema.Types.ObjectId,ref: "Company"},
created_at:{type: Date,required:true,default: Date.now},
updated_at:{type: Date,required:true,default: Date.now}
})
i am trying to query if my user logged is present on the supervisors list, an supervisor list of the establishment Schema is an array who do reference with the User model.. i'm trying to do this:
db.getCollection('establishments').find({supervisors: {$in:["5b58ef22bfee4a4589fbb6ba"]}})
this is a command that i run on the mongo console and this command return my row, when i try to do the same with mongoose, this command fails and return always null:
var establishment=await Establishment.find({ "supervisors": {"$in": [mongoose.Types.ObjectId(req.userInformation._id)]} });
What can i do to fix my problem? i had one day trying to fix this problems and i can find the solution. i'm making the most easy query but i want to do something like that:
Query the order schema and match only if the logged user is available on supervisors list of the Establishment Schema.
if you can help y will be very happy!
Upvotes: 0
Views: 62
Reputation: 4220
You can use $elemmatch:
db.getCollection('establishments').find({
supervisors:{
$elemMatch:{
$eq : ObjectId("5b58ef22bfee4a4589fbb6ba")
}
}
});
Upvotes: 1