Austin Hunter Austin Hunter - 1 month ago 15
Javascript Question

MongoDB $where is not working properly

I have looked around and tried all kinds of docs to be able to get the

$where
clause in MongoDB to work for me, but it just won't work.

Here is my object:



var UserProfiles = [{
userProfileID: "3f8c553c-3633-4fe9-a007-4346a783450c",
firstName: 'Austin',
lastName: 'Hunter',
email: 'ahunter8....com',
token: '',
platform: '',
password: 'admin',
companyProfileID: "86660a5b-7f61-4238-889d-1cc3087947b9",
authentication: ''
}....





there are several "profiles" inserted into the UserProfiles Object. That is just the first one.

Here is me inserting into the collection:



MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
} else {
console.log("We are connected");
}

var collection = db.collection('UserProfile');

for (var i = 0; i < UserProfiles.length; i++) {
collection.insert(UserProfiles[i], function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
});
}
db.close();
});





Now I am trying to search my collection for a passed in email AND companyProfileID. If they both match then return that profile. I thought the
$where
clause would be best but I can't get it to work.

Here is me trying to find():



function getUserProfile(passInEmail, companyID, callback) {
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
} else {
console.log("We are connected");
}
var collection = db.collection('UserProfile');
collection.find({$where: "this.email == passInEmail"}, function(err, result) {
if (err) {
console.log(err);
callback(err);
} else if (result.length) {
console.log(result);
callback(result);
} else {
callback(err);
console.log("No document found");
}
});
db.close();
});
}





I am trying to search the collection and if the object email matches the passed in email and the object companyProfileID matches the passed in companyID then success.

Answer

The $where clause in your case in not the best thing.
You should do simply:

//userIdParam ad emailParam are two variables 
collection.find({userProfileID: userIdParam, email: emailParam})
    .toArray(function(err, result) {
        if (err) {
            console.log(err);
            callback(err);
        } else if (result.length) {
            console.log(result);
            callback(result);
        } else {
            callback(err);
            console.log("No document found");
        } 
    });

Take a look of the doc here