考虑我有下表:
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)
使用 mongoose,如何使用产品名称而不是产品 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中使用$elemMatch:
$match: {
'ProductContainerTable': { $elemMatch: { name: productName }}
}
希望对你有帮助。