[英]How to filter documents using find method in mongoose based on the data from reference in documents?
I am working on e-commerce like app.我正在从事像应用程序这样的电子商务。 I have orderItem Schema我有 orderItem 模式
const orderItemsSchema = mongoose.Schema(
{
order: {
type: mongoose.Schema.Types.ObjectId,
ref: 'OrderItems',
required: true,
},
product: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Products',
required: true,
},
quantity: {
type: Number,
default: 1,
},
subCost: {
type: Number,
required: true,
},
},
{
timestamps: true,
}
);
Where product schema has a field "owner" which is also a reference.产品模式有一个字段“所有者”,这也是一个参考。
I am expecting to get orderItems based on owners of the products.我期望获得基于产品所有者的 orderItems。
For Example: A owner want to check which products of him has been sold.例如:某店主想查看他的哪些产品已经售出。 So he will query orderItems to get his sold items.因此他将查询 orderItems 以获取他出售的商品。
I'm not an expert in mongoose, so maybe the syntax is not entirely correct:我不是 mongoose 的专家,所以语法可能不完全正确:
// You get all products _id that owner currently sells
const yourOwnerObjectId = mongoose.Types.ObjectId(yourOwnerId); // Create the objectId from a string
const productsOwner = Products.find({owner: yourOwnerObjectId}).select({_id: 1})
// You get all orders that contains any of previous product _id
const orderWithProductsSold = OrderItems.find({_id: {$in: productsOwner}})
I'm not sure about what returns the first query regarding _id
.我不确定什么会返回关于_id
的第一个查询。 Maybe you have to do some type of casting to ObjectId
or whatever to perform the second query, but I think the idea is right.也许您必须对ObjectId
或其他任何类型进行某种类型的转换才能执行第二个查询,但我认为这个想法是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.