📜  https:stackoverflow.com 问题 19380738 mongoose-nested-query-on-model-by-field-of-its-referenced-model - Javascript (1)

📅  最后修改于: 2023-12-03 15:01:20.756000             🧑  作者: Mango

Mongoose嵌套查询

问题描述

在使用Mongoose进行嵌套查询时,如何按其引用模型的字段来对模型进行查询?

解决方法

可以使用Mongoose的populate()方法进行嵌套查询。具体步骤如下:

  1. 在模型中设置字段引用。

    const ProductSchema = new mongoose.Schema({
        name: String,
        price: Number,
        category: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Category'
        }
    });
    
  2. 使用populate()方法。

    Product.find()
        .populate({ path: 'category', match: { name: 'Electronics' } })
        .exec((err, products) => {
            console.log(products);
        });
    

    在path中传递字段引用的名称(即在模型中设置的name),在match中设置查询条件即可。

完整代码
const mongoose = require('mongoose');

const CategorySchema = new mongoose.Schema({
    name: String
});

const ProductSchema = new mongoose.Schema({
    name: String,
    price: Number,
    category: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Category'
    }
});

const Category = mongoose.model('Category', CategorySchema);
const Product = mongoose.model('Product', ProductSchema);

mongoose.connect('mongodb://localhost/nested_query');

const ipad = new Product({
    name: 'iPad Air',
    price: 799,
    category: new Category({ name: 'Electronics' })
});

ipad.save((err, savedProduct) => {
    Product.find()
        .populate({ path: 'category', match: { name: 'Electronics' } })
        .exec((err, products) => {
            console.log(products);
            mongoose.disconnect();
        });
});
参考资料