简体   繁体   中英

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

I am bit new to mongodb and javascript, So please forgive me for any mistakes or silly questions:

I have created a javascript which logs in to the database and runs multiple queries but the script is running fine till its login to the database but fails to run the query.

Below is the error:

$ 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' }

But when i ran the same query in mongo shell i am getting the output but when i run in javascript it fails, I understand that it is expecting the $in values as an array which i tried to fix but failed.

Below is the query: Edited

I am storing the output of a query which is an array in "QuoteId Variable and then putting it with $in condition but it does not work.

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) => {

try this query:

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

Edit

The Problem is with var QuoteId = collectionA.distinct('QuoteId'); because distinct method needs a callback to actually return the distinct QuoteIds

try this:

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
    }
});

This is because Nodejs is async in nature collectionA.distinct('QuoteId') will not return results right away, it will either need a callback (as above) or will return a Promise object

MongoDB nodejs driver For reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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