mongodb Mongoose:从2个集合中获取数据,例如获取具有相同类别类型(如水果)的产品

6ioyuze2  于 2023-01-25  发布在  Go
关注(0)|答案(2)|浏览(115)

我对mongoDBmongoose非常陌生,我也知道像这样的问题已经被问到了,但我仍然没有得到任何运气。
所以我尝试做的是我有2个集合,一个是产品,第二个是类别,我试图得到的产品是类别类型:水果

产品型号js

const mongoose = require('mongoose')

const productSchema = new mongoose.Schema({
    category: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Category'
    },
    name: {
        type: String,
        required: true,
        unique: true
    },
    price: {
        type: Number,
        required: true
    },
    image: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    }
})

const Product = mongoose.model('Product', productSchema)

module.exports = Product

类别.型号.js

const mongoose = require('mongoose')

const categorySchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        unique: true,
        lowercase: true
    }
})

const Category = mongoose.model('Category', categorySchema)

module.exports = Category

产品收集

[ { _id: 5ffc9795355f3707ec326f51,
    name: 'apple',
    price: 80,
    image: 'apple1.jpg',
    description:
     'Do you really need description for this ??',
    category: 5ffc94e8a7542a37101a119c,
    __v: 0 },
  { _id: 5ffd54409793c33b183376b8,
    name: 'Beef',
    price: 180,
    image: 'beef1.jpg',
    description: 'Don\'t you dare to ask about beef in india',
    category: 5ffc94dda7542a37101a119b,
    __v: 0 },
  { _id: 5ffd54969793c33b183376b9,
    name: 'Mango',
    price: 100,
    image: 'mango1.jpg',
    description:
     'Have some manog because you cannot eat the bottle of slice like katrina kaif do, its crazy',
    category: 5ffc94e8a7542a37101a119c,
    __v: 0 } ]

类别集合

[ { _id: 5ffc947ea7542a37101a119a, name: 'vegitables', __v: 0 },
  { _id: 5ffc94dda7542a37101a119b, name: 'non-veg', __v: 0 },
  { _id: 5ffc94e8a7542a37101a119c, name: 'fruits', __v: 0 } ]

现在我想获取类别为水果的产品

我知道我必须使用聚合和查找,我也尝试过,但没有得到任何运气,这是我的代码

const Product = require('./models/product')
const Category = require('./models/category')

const test = async () => {
    try {
        var query = [
            {
            $lookup: {
                from: "product",
                localField: "category",
                foreignField: "_id",
                as: "product"
            }
        }]
        const productCate = await Product.aggregate(query)
        console.log(productCate)
        // const productCat = await Product.find().populate({
        //     path: 'category',
        //     match: {name: 'fruits'}
        // }).exec()
        // console.log(productCat)
    }catch(e) {

    }
}

test()

更新-1

我也尝试了ppuplate,但仍然没有得到预期的响应,这是我的代码:

const test = async () => {
    try {
        const productCat = await Product.find().populate({
            path: 'category',
            match: {name: 'fruits'}
        }).exec()
        console.log(productCat)
    }catch(e) {

    }
}

test()

这是我的输出

[ { _id: 5ffc9795355f3707ec326f51,
    name: 'apple',
    price: 80,
    image: 'apple1.jpg',
    description:
     'Do you really need description for this, how dumb are you ??',
    category: { _id: 5ffc94e8a7542a37101a119c, name: 'fruits', __v: 0 },
    __v: 0 },
  { _id: 5ffd54409793c33b183376b8,
    name: 'Beef',
    price: 180,
    image: 'beef1.jpg',
    description: 'Don\'t you dare to ask about beef in india',
    category: null,
    __v: 0 },
  { _id: 5ffd54969793c33b183376b9,
    name: 'Mango',
    price: 100,
    image: 'mango1.jpg',
    description:
     'Have some manog because you cannot eat the bottle of slice like katrina kaif do, its crazy',
    category: { _id: 5ffc94e8a7542a37101a119c, name: 'fruits', __v: 0 },
    __v: 0 } ]

这里我还得到了牛肉,这是属于非蔬菜类,但与类别空。实际上,我只想水果类产品。

mepcadol

mepcadol1#

您可以按照以下代码

const test = async () => {
  try {
    let categoryId = await Category.findOne({name:"fruits"}).select("_id")
      const productCat = await Product.find({category:categoryId}).populate(
        "category"
      ).lean()
      console.log(productCat)
  }catch(e) {

  }
}

test()
hwamh0ep

hwamh0ep2#

您可以在不使用聚合的情况下使用填充匹配:

Product.find().populate({
path: 'category',
match: { 'name': 'fruits' }
  })
 .exec()

相关问题