0

I am trying to create a query object for mongoose, so

let countryCondition = {};
searchQuery = {
    "$text": {
        "$search": searchString
    }
};
query = {
    searchQuery,
    countryCondition
};
console.log('$query:', query);

When i console.log query, i see the ouput as,

$query: { 
    searchQuery: { 
        '$text': { 
            '$search': '2017' 
         } 
    },
    countryCondition: {} 
}

but i need

[{ '$text': { '$search': '2017' } }, {}]
2
  • 2
    maybe do you need [{ '$text': { '$search': '2017' } }, {}]? Commented May 9, 2017 at 8:27
  • @Slavik yes if its ok for mongodb Commented May 9, 2017 at 8:30

3 Answers 3

2

As Slavik mentioned, you're probably looking for an array rather than an object:

[{ '$text': { '$search': '2017' } }, {}]

since objects must have names for their parameters.

Try this:

let query = [
  searchQuery,
  countryCondition
];
Sign up to request clarification or add additional context in comments.

Comments

0

If you really need to combine the objects in one use Object.assign

let countryCondition = {
    country: 'Spain'
};

let searchQuery = {
    '$text': {
        '$search': 'sometext'
    }
};

let query = Object.assign(searchQuery, countryCondition);

console.log(query);

Comments

0

If you'r looking for an or condition your object should be like

{ $or: [ { text: "search text" }, { country: "xyz" } ] } 

If you'r looking for an and condition then you can combine two objects following Diego's answer

{text : {}, country : {}}

You can get the first object like

let query = {};
query['$or'] = [];

query['$or'].push({'text' : 'some text'});
query['$or'].push({'country' : 'xyz'});

Comments

Your Answer

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