繁体   English   中英

Mongo DB查询在Javascript中给出错误,但在mongo shell中运行平稳

[英]Mongo DB query giving error in Javascript but run smoothly in mongo shell

我对mongodb和javascript有点陌生,所以如果有任何错误或愚蠢的问题,请原谅我:

我创建了一个Javascript,该Javascript登录到数据库并运行多个查询,但是脚本运行良好,直到登录到数据库,但无法运行查询。

下面是错误:

$ node Test_Script.js
Successfully Connected to Database
{ MongoError: $in needs an array
at Function.MongoError.create (C:\PROJECT\DOCS\Requirements Documents\User 
Stories\CPQ\1125\node_modules\mongodb-core\lib\error.js:31:11)
at queryCallback (C:\PROJECT\DOCS\Requirements Documents\User 
Stories\CPQ\1125\node_modules\mongodb-core\lib\cursor.js:212:36)
at C:\PROJECT\DOCS\Requirements Documents\User 
Stories\CPQ\1125\node_modules\mongodb-core\lib\connection\pool.js:469:18
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
name: 'MongoError',
message: '$in needs an array',
ok: 0,
errmsg: '$in needs an array',
code: 2,
codeName: 'BadValue' }

但是,当我在mongo shell中运行相同的查询时,我得到了输出,但是当我在javascript中运行时,它失败了,我知道它期望将$ in值作为我试图修复但失败的数组。

下面是查询:编辑

我将查询的输出存储在“ QuoteId变量”中,然后将其置于$ in条件下,但它不起作用。

var QuoteId = collectionA.distinct('QuoteId');


var query = {$and: [{"created" : {$lte: new Date(new Date().setDate(new 
Date().getDate()- 40))}}, {"id": {$in:QuoteId}}]}
//var purgeDays = 
db.collection('SCPQ_QuoteCleanup_Config).distinct("PurgeDays")



collection.find(query).toArray((err, doc) => {

试试这个查询:

var query = {$and: [{"created" : {$lte: new Date(new Date().setDate(new 
Date().getDate()- 40))}}, {"id": {$in:[QuoteId]}}]}

编辑

问题出在var QuoteId = collectionA.distinct('QuoteId'); 因为不重复的方法需要回调才能实际返回不重复的QuoteIds

尝试这个:

collectionA.distinct('QuoteId', (err, res) => {
    if (err) {
        // register error
    } else {
        var QuoteId = res;
        var query = {$and: [{"created" : {$lte: new Date(new Date().setDate(new 
        Date().getDate()- 40))}}, {"id": {$in:QuoteId}}]}
        // put your code here
    }
});

这是因为Node.js在本质上是异步的collectionA.distinct('QuoteId')不会立即返回结果,它要么需要callback (如上所述),要么将返回Promise对象

MongoDB Node.js驱动程序供参考

暂无
暂无

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

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