yycctt yycctt - 3 months ago 30
Node.js Question

cannot build an '$or' query in node.js with mongodb

I want to append an $or query conditionally, but the query cannot receive the data which I want to search in the db

It just keeps telling me:


"Error :MongoError: Can't canonicalize query: BadValue $and/$or/$nor must be a nonempty array"


or if I initialize the query.$or as {}


"Error :MongoError: Can't canonicalize query: BadValue $or needs an array"


Thank!

For example:



var user = {
name:"Toby",
gender:"Female",
contact:[
{email:"123@gmail.com"},
{email:"APPLE@gmail.com"},
{email:"news456@gmail.com"}]};
var query = {};
var q = ['123@gmail.com','news456@gmail.com'];
query.name = user.name;
if(user.contact!=null){
query.$or = [];
query.$or['contact.0.email'] = q[0];
query.$or['contact.1.email'] = q[1];
}




Answer

$or needs to be an array of possible match conditions. You could do:

var user = {
      name:"Toby",
      gender:"Female",
      contact:[
        {email:"123@gmail.com"},
        {email:"APPLE@gmail.com"},
        {email:"news456@gmail.com"}]};
var query = {};
var q = ['123@gmail.com','news456@gmail.com'];
query.name = user.name;
if(user.contact!=null){
  query.$or = [];
  query.$or.push({'contact.email': q[0]});
  query.$or.push({'contact.email': q[1]});
}
Comments