【问题标题】:Is there any way to use Model.find() Querie with populated field filter in node.js有没有办法在 node.js 中使用 Model.find() 查询和填充字段过滤器
【发布时间】:2021-10-12 21:42:23
【问题描述】:

我正在使用这样的 Model.find() 查询

const model = require("../../models/product");

module.exports = async(filters) => {
        let data = Object.values(filters.data)[0]
        let field = Object.keys(filters.data)[0];
        const regex = new RegExp(escapeRegex(data), 'gi');
        return await model.find({ $or: [{
                [field]: regex }] }).populate("division_id").populate("type_id").populate("category_id").exec()
    }
    //$or:[ {'_id':objId}, {'name':param}, {'nickname':param} ]
function escapeRegex(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};

过滤器

在过滤器中,我正在发送 { data : { name : "a" } }

这是给所有名称以“a”开头的产品,这很好!

但现在我想获得具有特定划分的过滤结果

响应仅包括特定的部门产品

产品架构

_id: mongoose.Schema.Types.ObjectId,

division_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Division', required: [true, "Product Division Id is required"] },

name: { type: String, required: [true, "Product Name is required"] },

部门架构

_id: mongoose.Schema.Types.ObjectId,

name:{ type: String, required: "Division Name is required" },

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    尝试使用此处的示例:https://mongoosejs.com/docs/populate.html#query-conditions

    所以我认为它应该是这样的:

    return await model.find({
      $or: [
        { [field]: regex } // By the way, if it's the only query in $or, you don't need $or
      ],
    }
    .populate({
      path: "division_id",
      match: { _id: <ObjectId> }
    })
    .populate("type_id")
    .populate("category_id")
    .exec();
    

    第一个 .populate 将被扩展一点以包含特定匹配。在那里,您可以传递_id(例如,或name,根据您的架构)来匹配特定的部门。

    【讨论】:

    • 感谢您的回复......但我仍然收到错误“无法读取 null 的属性 '_id'”
    • @user16452247 这必须在其他行,因为我的代码没有可为空的对象
    猜你喜欢
    • 2013-08-07
    • 2018-05-25
    • 2021-03-23
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2010-12-11
    相关资源
    最近更新 更多