Node.js NodeJS+MongoDB:find()具有特定条件
我不知道怎么做,所以我需要你的建议。我有4个复选框的表格:Node.js NodeJS+MongoDB:find()具有特定条件,node.js,mongodb,database,Node.js,Mongodb,Database,我不知道怎么做,所以我需要你的建议。我有4个复选框的表格: <input type="checkbox" class="checkbox" id="check_stain"> <input type="checkbox" class="checkbox" id="check_black"> <input type="checkbox" class="checkbox" id="check_titan"> <input type="checkbox" cl
<input type="checkbox" class="checkbox" id="check_stain">
<input type="checkbox" class="checkbox" id="check_black">
<input type="checkbox" class="checkbox" id="check_titan">
<input type="checkbox" class="checkbox" id="check_special">
值是简单的字符串。因此,我需要获取每个对象,其中指定的复选框为true,但不包括那些未定义的对象。换句话说,我想创建一个简单的搜索算法。让我给你们举个例子:我们检查污点,我们应该得到每一个污点真实的物体。也许其他值为真/假并不重要。如果我们选择check_stain和check_black,我们得到的对象的stain&black=true,其他字段不感兴趣
我总是发现这样的代码:
collection.find({ %my-condition% } ,function(err, companies) {
companies.each(function(err, company){
//do smth with found
});
});
但我不知道如何写条件才能找到。我想,我应该在请求中使用$or运算符。我看了文件,但还是看不懂。谢谢
更新:嗯,这似乎是我问题的解决方案:
例如,黑色和污渍是正确的:
var condition = {
"stain": "false",
"black": "true",
"titan": "false",
"special": "true",
}
for (var i in condition) {
if (condition[i] != "true") {
delete condition[i];
}
}
collection.find(condition ,function(err, companies) {
companies.each(function(err, company){
//do smth with found
});
});
问题出在哪里?只需创建一个具有正确关键点的对象,而不使用其他关键点。我不确定我是否正确理解您。在具有collection.insert的数据库中或在何处创建新对象?如我所知,您建议将此对象作为查找请求的参数发送,或者什么?stain应该是true:collection.find{stain:true}stain&black应该是true:collection.find{stain:true,black:true}我知道,但是如果我不知道哪些值是true,我如何创建条件?正如您所理解的,我不应该在请求中包含错误的值。正确的将是smth样的收集。查找{ifcheck_stain stain stain:true,ifcheck_black black:true…}但正如您所知,我不能做这样的请求…谢谢您,给我一些时间检查您的代码。我仍然不知道它是如何工作的…只是从条件对象中删除所有不正确的键。我已经更新了我的帖子。这是我写的代码。我已经祈祷并启动了它:嗯,它似乎工作正常:非常感谢!
if (req.body.sort_query == 'req-steel') {
var condition = {}
if (req.body.check_stain == "on") {condition['stain'] = 'true';}
if (req.body.check_black == "on") {condition['black'] = 'true';}
if (req.body.check_titan == "on") {condition['titan'] = 'true';}
if (req.body.check_other == "on") {condition['special'] = 'true';}
for (var i in condition) {
if (condition[i] != "true") {
delete condition[i];
}
}
var companies_list = new Array();
collection.find(condition, function (err, companies) {
companies.each(function (err, company) {
//do smth
});
});
};
var condition = {
"stain": "false",
"black": "true",
"titan": "false",
"special": "true",
}
for (var i in condition) {
if (condition[i] != "true") {
delete condition[i];
}
}
collection.find(condition ,function(err, companies) {
companies.each(function(err, company){
//do smth with found
});
});