javascript - Mongoose.Find() 与数组和 OR 运算符

标签 javascript node.js mongodb mongoose mongodb-query

我正在尝试搜索与 json 对象匹配的数据库行。

示例:

var searchParams = {
    city: ['New York City', 'Budapest'], 
    jobs: ['Assistent'] //Can be multiple 
}

//If "city" is equal to one of the searchParams.city variables
//AND jobs is equal to one of the searchParams.jobs variables

var searchQuery = {
    $and: [
        {$or: clean_city},
        {$or: clean_cat}
    ]
}

Jobs.find(searchQuery, function(err, list){
    console.log(list);
});

我已经尝试了在谷歌上可以找到的所有选项,但似乎没有任何选项适用于数组。

如果有人能提供帮助,我将非常感激。

问候

最佳答案

你可以找到一个例子here在您的上下文中,这使得假设:

  • 使用 searchParams 因为我不知道 clean_* 变量中有什么
  • 数据库字段为cityjob
{
  $and: [
    { $or: searchParams.city.map(city => ({ city })) },
    { $or: searchParams.jobs.map(job => ({ job })) }
  ]
}

这是更短的语法(如果数据库字段名称不同,您无法简化它):

{
  $and: [
    { $or: searchParams.city.map((city) => { return { city: city }; }) },
    { $or: searchParams.city.map((job) => { return { job: job }; }) }
  ]
}

关于javascript - Mongoose.Find() 与数组和 OR 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54921530/

相关文章:

javascript - 如何在页面加载时隐藏另一个 php 文件中的 div

javascript - 从 angularjs 调用 REST 服务时本地主机上的 CORS 问题

javascript - 将测验问题存储在对象数组中

mongodb - 如何在 Mongoose 中使用枚举验证字符串数组?

javascript - MongoDB 查找和修改

javascript - 当模式位于单独的文件中时,创建模型时是否存在任何问题?

javascript - 无法替换\r 字符

node.js - 在 Meteor 中进行异步 (node.js)

javascript - 如何检测使用 Node.js 连接的 USB 设备

node.js - Browserify + browserify-ngannotate + Tsify 不工作