如何使用参考域在猫鼬中找到



考虑我有下表:

const ImageSchema = new mongoose.Schema({
name: {
type: String,
},
url: {
type: String,
},
createdAt: {
type: Date,
default: Date.now(),
},
updatedAt: {
type: Date,
default: Date.now(),
},
})
module.exports = mongoose.model("Image", ImageSchema) 

另一个使用上述集合作为参考的集合:

const ProductSchema = new mongoose.Schema(
{
name: {
type: String,
required: [true, "Please add a product name"], 
},

photos: {
type: [mongoose.Schema.ObjectId],
ref: "Image",
},
createdAt: {
type: Date,
default: Date.now,
},
updatedAt: {
type: Date,
default: Date.now,
},
},
)
module.exports = mongoose.model("Product", ProductSchema)

然后是另一个使用这些集合的集合:

const ContainerSchema = new mongoose.Schema(
{
name: {
type: String,
required: [true, "Please add a product name"], 
},

products: {
type: [mongoose.Schema.ObjectId],
ref: "Product",
},
images: {
type: [mongoose.Schema.ObjectId],
ref: "Image",
},
createdAt: {
type: Date,
default: Date.now,
},
updatedAt: {
type: Date,
default: Date.now,
},
},
)
module.exports = mongoose.model("Container", ContainerSchema)

使用猫鼬,我如何使用产品名称而不是产品id来查询(查找(容器?

我的意思是,我可以通过这种方式找到使用产品id的容器:

const container = await Container.find({product : product_id});

但我希望找到使用产品名称的容器。此外,请记住,这些产品被用作容器中的数组,我如何使用产品名称找到容器?

聚合方法可能会更好地获得这些值。

由于Products是一个数组,我们需要使用$elemMatch".$">标记以搜索到Products数组。所以

const container = await Container.aggregate([
{
$lookup:{
from:'products',
localField:'products',
foreignField:'_id',
as:'ProductContainerTable'
}
},
{
$match: {
'ProductContainerTable.$.name' : productName
},
}
])

$match条件将被创建为;

{'ProductContainerTable': {$elemMatch: {name: productName }}}

希望,这对你有帮助。

最新更新