簡體   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