Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if values matchs in MongoDB [duplicate]

I want to check with mongodb if nickname and password are true im trying to use the $and operator with $regex but I can't get it work. Can someone help me a hand with it currently have this;

checkNickname: function(nickname, password){
    var reNick = new RegExp(nickname, "i"),
        rePass = new RegExp(password, "i");
    getProfile.find( { $and :  [{
        nickname: { $ne: { $regex: reNick } } },
        { password: { $ne: { $regex: rePass} } } 
    ]}, function(data){
        console.log(data)
    });
},
like image 364
I NA Avatar asked Nov 12 '15 19:11

I NA


People also ask

How do you stop duplicates in MongoDB?

To insert records in MongoDB and avoid duplicates, use “unique:true”.

What is $project in MongoDB?

The $project takes a document that can specify the inclusion of fields, the suppression of the _id field, the addition of new fields, and the resetting of the values of existing fields. Alternatively, you may specify the exclusion of fields. The $project specifications have the following forms: Form. Description.


2 Answers

This will do it for you,

    checkNickname: function(nickname, password){
        var reNick = new RegExp("/^" + nickname + ".*/", "i"),
            rePass = new RegExp("/^" + password + ".*/", "i");
        getProfile.find({ 
                    nickname: { $not: reNick },  
                    password: { $not: rePass }
            }, function(err, data) {
            console.log(data)
        });
    }
like image 117
Hakan Kose Avatar answered Oct 05 '22 11:10

Hakan Kose


As mention you can't have $regex as argument to $ne but you can negate your regex.

checkNickname: function(nickname, password){
    var reNick = RegExp("^((?!"+nickname+").)*$", "i");
    var rePass = new RegExp("^((?!"+password+").)*$", "i");
    getProfile.find( { nickname: reNick, password: rePass }, function(err, data) {
        console.log(data)
    });
};
like image 41
styvane Avatar answered Oct 05 '22 10:10

styvane