我正在尝试使用快速猫鼬模型中的填充物进行搜索,然后在猫鼬中填充后进行查询,看看我到底想要什么

时间:2019-01-30 07:29:53

标签: node.js mongodb mongoose mongoose-schema mongoose-populate

我一般来说对Mongoose和MongoDB还是陌生的,所以我很难确定这样的事情是否可行:

我正在尝试仅过滤那些created_by_id不是[]的文档。

这是架构。

var CampaignSchema = new Schema({
   name: { type: String, required: true },
   description: { type: String, required: true },
   budget: { type: String, required: true },
   tags: { type: [ String ], required: true },
   status: { type: Number },
   payment_id: { type: String },
   created_by_id: [{ type: Schema.Types.ObjectId, ref: 'User' }],
   attached_file: { 
      uploaded_on: { type: Date, default: Date.now },
      uploaded_by: { type: String, required: true },
  },
  added_url: {
     added_on: { type: Date, default: Date.now },
     added_by: { type: String, required: true },
  },
  updated_by: { type: String },
  created_on: { type: Date, default: Date.now },
  updated_on: { type: Date }

});

这是代码:

_getCampaigns(req, res){

    var token = helpersMethods.getToken(req.headers);
    var page = parseInt(req.query.page) || 0; //for next page pass 1 here
    var limit = parseInt(req.query.limit) || 10;

    var term = new RegExp(req.query.search, 'i');
    var obj = { "created_by_id": { "$ne": [] } };

    if (token) {
        Campaign.find(obj)
            .populate({ 
                path  : 'created_by_id',
                match : {
                    $or: [
                            { name: { $regex: term }},
                        ]
                }
            })
            .sort({ updateAt: -1 })
            .skip(page * limit) 
            .limit(limit)
            .exec((err, doc) => {
                if (err) {
                    return res.json(err);
                }
                Campaign.count(obj).exec((count_error, count) => {
                    if (err) {
                        return res.json(count_error);
                    }
                    return res.json({
                        total: count,
                        page: page,
                        pageSize: doc.length,
                        campaigns: doc
                    });
                });
            });
    } else {
        return res.status(403).send({success: false, msg: 'Unauthorized.'});
    }

}

我正在得到这样的邮递员输出,但是我不希望没有created_by_id数组的对象:

{
"total": 2,
"page": 0,
"pageSize": 2,
"campaigns": [
    {
        "attached_file": {
            "uploaded_by": "Demo user",
            "uploaded_on": "2019-01-29T11:07:27.475Z"
        },
        "added_url": {
            "added_by": "Demo user",
            "added_on": "2019-01-29T11:07:27.475Z"
        },
        "tags": [
            "tag1",
            "tags2"
        ],
        "_id": "5c5033ef28f63c72808f2225",
        "created_by_id": {
            "_id": "5c4965d477e7191c4d40b412",
            "name": "Demo user",
            "email": "demo@arth.tech",
            "phone": "9918XXXXXX",
            "type": "1",
            "admin_rights": "1",
            "password": "$2a$10$6T2ulNN60fBG9/vFgf8XhetkcWb/2zDxGXUMXMRi2Bltn8s1NEkbq",
            "__v": 0,
            "createdAt": "2019-01-24T07:31:03.327Z",
            "loggedIn_at": "2019-01-30T06:33:04.388Z",
            "loggedOut_at": "2019-01-24T08:03:44.091Z"
        },
        "name": "Test Campaign",
        "description": "Discription of test campaign",
        "budget": "2000",
        "updated_by": "Demo User",
        "created_on": "2019-01-29T11:07:27.475Z",
        "__v": 0
    },
    {
        "attached_file": {
            "uploaded_by": "Demo User",
            "uploaded_on": "2019-01-29T13:08:48.021Z"
        },
        "added_url": {
            "added_by": "Demo user",
            "added_on": "2019-01-29T13:08:48.021Z"
        },
        "tags": [
            "test1",
            "test2"
        ],
        "_id": "5c505060b97f871123d97990",
        "created_by_id": [],
        "name": "Hello Campaign",
        "description": "Description of Hello campaign",
        "budget": "1000",
        "updated_by": "Hello user",
        "created_on": "2019-01-29T13:08:48.021Z",
        "__v": 0
    }
]

}

我只想要那些具有created_by_id(我想要的实际输出)的对象。

{
"total": 1,
"page": 0,
"pageSize": 1,
"campaigns": [
    {
        "attached_file": {
            "uploaded_by": "Demo user",
            "uploaded_on": "2019-01-29T11:07:27.475Z"
        },
        "added_url": {
            "added_by": "Demo user",
            "added_on": "2019-01-29T11:07:27.475Z"
        },
        "tags": [
            "tag1",
            "tags2"
        ],
        "_id": "5c5033ef28f63c72808f2225",
        "created_by_id": {
            "_id": "5c4965d477e7191c4d40b412",
            "name": "Demo user",
            "email": "demo@arth.tech",
            "phone": "9918XXXXXX",
            "type": "1",
            "admin_rights": "1",
            "password": "$2a$10$6T2ulNN60fBG9/vFgf8XhetkcWb/2zDxGXUMXMRi2Bltn8s1NEkbq",
            "__v": 0,
            "createdAt": "2019-01-24T07:31:03.327Z",
            "loggedIn_at": "2019-01-30T06:33:04.388Z",
            "loggedOut_at": "2019-01-24T08:03:44.091Z"
        },
        "name": "Test Campaign",
        "description": "Discription of test campaign",
        "budget": "2000",
        "updated_by": "Demo User",
        "created_on": "2019-01-29T11:07:27.475Z",
        "__v": 0
    }
]

}

有什么可以帮助的吗?

1 个答案:

答案 0 :(得分:0)

我做到了,我想要什么。这是更新的代码。

_getCampaigns(req, res){

    var token = helpersMethods.getToken(req.headers);
    var page = parseInt(req.query.page) || 0; //for next page pass 1 here
    var limit = parseInt(req.query.limit) || 10;

    var term = new RegExp(req.query.search, 'i');
    var obj = {};

    if (token) {
        Campaign.find(obj)
            .populate({ 
                path  : 'created_by_id',
                match : {
                    $or: [
                            { name: { $regex: term }},
                        ]
                }
            })
            .sort({ updateAt: -1 })
            .skip(page * limit) 
            .limit(limit)
            .exec((err, docs) => {
                if (err) {
                    return res.json(err);
                }else{
                    docs = docs.filter(function(doc) {
                        return doc.created_by_id.length != 0;
                    });
                    Campaign.count(obj).exec((count_error, count) => {
                        if (err) {
                            return res.json(count_error);
                        }else{
                            return res.json({
                                total: count,
                                page: page,
                                pageSize: docs.length,
                                campaigns: docs
                            });
                        }

                    });
                }

            });
    } else {
        return res.status(403).send({success: false, msg: 'Unauthorized.'});
    }

}