使用javascript将两个对象组合为一个对象

时间:2017-05-09 08:25:08

标签: javascript node.js

我正在尝试为mongoose创建一个查询对象,所以

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

当我 console.log 查询时,我将输出视为

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

但我需要

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

3 个答案:

答案 0 :(得分:2)

正如斯拉维克所说,你可能正在寻找一个数组而不是一个对象:

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

因为对象必须具有其参数的名称。

试试这个:

let query = [
  searchQuery,
  countryCondition
];

答案 1 :(得分:1)

如果您确实需要将对象组合在一起,请使用Object.assign



let countryCondition = {
    country: 'Spain'
};

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

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

console.log(query);




答案 2 :(得分:0)

如果你正在寻找或者你的对象应该是

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

如果您正在寻找和条件,那么您可以按照Diego的回答结合两个对象

{text : {}, country : {}}

你可以得到像

这样的第一个对象
let query = {};
query['$or'] = [];

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