1

我正在使用这样的 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" },

4

1 回答 1

0

尝试使用此处的示例: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根据您的架构)来匹配特定的部门。

于 2021-08-09T10:23:21.920 回答