These are chat archives for Automattic/mongoose

2nd
Nov 2018
Berian
@chaiwa-berian
Nov 02 2018 15:13
Hi all. Kindly advise why the schema for the national_id field is always passing validation even if a wrong/value not in the enum list is passed?:
national_id: {
        type: {
            id_type: {
                type: String,
                 enum: ['national_id','passport_id', 'driving_license'],
                 required: true
            },
            id_value: {
                type: String,
                validate: {
                    validator: function(v, callback) {
                        //conditionally run validation based on type of id passed 
                        return true;
                    }
                }
            }
        }
Berian
@chaiwa-berian
Nov 02 2018 16:59

Hi all. Kindly advise why the schema for the national_id field is always passing validation even if a wrong/value not in the enum list is passed?:

national_id: {
        type: {
            id_type: {
                type: String,
                 enum: ['national_id','passport_id', 'driving_license'],
                 required: true
            },
            id_value: {
                type: String,
                validate: {
                    validator: function(v, callback) {
                        //conditionally run validation based on type of id passed 
                        return true;
                    }
                }
            }
        }

I kinda resolved it! The schema was nested as a sub-document, so I had to refactor into its own schema and now all things glorious! Of course with the help of mongoose docs. :)

Maurizio Bellemo
@mbellemo_twitter
Nov 02 2018 21:32
@lineus I tried to create the index as you suggested, but I get an error from the endpoint
{
    "ok": 0,
    "errmsg": "text index required for $text query",
    "code": 27,
    "codeName": "IndexNotFound",
    "name": "MongoError"
}
The new endpoint looks like
router.get('/:id/feedbacks/', authenticate(['user']), (req, res) => {
    const filter = {
        company_id: req.user.company_id,
        project_id: req.params.id
    };
    if (req.query.search) {
        filter.$text = { $search: req.query.search };
    }

    const perPage = 25
    const page = req.query.page || 1

    Feedback.find(filter)
        .skip((perPage * page) - perPage)
        .limit(perPage)
        .then((feedbacks) => {
            Feedback.countDocuments(filter)
                .then((count) => {
                    res.send({
                        feedbacks,
                        current: page,
                        pages: Math.ceil(count / perPage),
                        total: count
                    });
                })
        }, (e) => {
            res.status(400).send(e);
        });
});
and I registered the index in the model file
FeedbackSchema.index({ title: 'text', description: 'text' });
any suggestions?