简体   繁体   English

Node.js Mongo DB查找查询未按预期工作

[英]Node.js Mongo DB find query doesn't work as expected

Please help me find error in my code 请帮助我在我的代码中发现错误

const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
var a = "2018";
var b = "December";
var c = "12";
var temp = "17";

var query = `{'${b}.${c}.temp':'${temp}'}`;
console.log(query);

MongoClient.connect(url,{ useNewUrlParser: true },(err, client) => {
    if (err){
      return console.log('Unable to login to Mongo DB');
    }
    const db = client.db('test'); 
 db.collection('updateTest').find(query).toArray()
.then((result) =>{
    if(err){
        return console.log(err);
    }if(result.length > 0){
        console.log(JSON.stringify(result));
    }else{
        console.log(JSON.stringify({Error:"Cannot find request"}));
    }
});
client.close();
});

When I use condition directly in the find({"December.12.temp":temp}) it works fine 当我直接在find({“ December.12.temp”:temp})中使用条件时,它可以正常工作

When I assign condition to a variable and use it in find(query) it works fine. 当我将条件分配给变量并在find(query)中使用它时,它可以正常工作。

var query = {"December.12.temp":temp};

But when I assign a value from input by user the query doesn't work as expected instead works as if no condition was specified. 但是,当我从用户输入中分配值时,查询无法按预期运行,而是像未指定条件那样运行。

var query = `{'${b}.${c}.temp':'${temp}'}`;

When you use backticks (``), query variable becomes a string, after all the JavaScript embedded in it has executed (ie using the values of b and c). 当您使用反引号(``)时,查询变量变成字符串,执行完嵌入其中的所有JavaScript后(即使用b和c的值)。 You actually require the query variable to be an object, not a string. 实际上,您要求查询变量是一个对象,而不是字符串。 Thus it fails. 因此它失败了。 Have a look at this doc Ps: I ended up answering in comments too. 看看这个文档 Ps:我最终也发表了评论。

var a = "2018";
var b = "December";
var c = "12";
var temp = "17";
var query = {};

var value = '${b}.${c}.temp';

query[value] = temp;

db.collection('updateTest').find(query).toArray()
.then((result) =>{
    if(err){
       return console.log(err);
    }if(result.length > 0){
        console.log(JSON.stringify(result));
    }else{
        console.log(JSON.stringify({Error:"Cannot find request"}));
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM