0

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:"[email protected]"},
        {email:"[email protected]"},
        {email:"[email protected]"}]};
var query = {};
var q = ['[email protected]','[email protected]'];
query.name = user.name;
if(user.contact!=null){
  query.$or = [];
  query.$or['contact.0.email'] = q[0];
  query.$or['contact.1.email'] = q[1];
}

2
  • The SQL command like that: SELECT * FROM user WHERE email='[email protected]' OR email='[email protected]' AND name='Toby' Commented Aug 11, 2016 at 8:07
  • Thank for your answer! And another solution found too:query1.contact={$elemMatch:{email:{}}};query1.contact.$elemMatch.email.$in=q; Commented Aug 11, 2016 at 8:51

1 Answer 1

2

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

var user = {
      name:"Toby",
      gender:"Female",
      contact:[
        {email:"[email protected]"},
        {email:"[email protected]"},
        {email:"[email protected]"}]};
var query = {};
var q = ['[email protected]','[email protected]'];
query.name = user.name;
if(user.contact!=null){
  query.$or = [];
  query.$or.push({'contact.email': q[0]});
  query.$or.push({'contact.email': q[1]});
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.