2015-03-30 183 views
2

使用Node.js和Mongo(mongodb驅動程序)將項目添加到集合。 我有一個使用socket.io將通知傳遞給頁面的html網站。我可以插入到數據庫中,但是當我嘗試查看是否存在值時,我從Mongo得到一個奇怪的回報。我發過一個名字並嘗試將它放入客戶端集合中。 我至今是:mongodb檢查是否存在值(node.js)

socket.on('DB', function(msg) 
    { 
     if(msg.Status == "Read") 
     { 
      MongoClient.connect(url, function(err, db) //connect to mongo 
      { 
       var collection = db.collection('Clients'); // get reference to the collection 
       collection.find(({Name: msg.Name},{$exists: true}), function(err, doc) //find if a value exists 
       {  
        if(doc) //if it does 
        { 
         console.log(doc); // print out what it sends back 
        } 
        else if(!doc) // if it does not 
        { 
         console.log("Not in docs"); 
        } 
       }); 
       db.close(); 
      }); 

      } 
} 

這將返回我:

{ connection: null, 
    server: null, 
    disconnectHandler: 
    { s: { storedOps: [], storeOptions: [Object], topology: [Object] }, 
    length: [Getter] }, 
    bson: {}, 
    ns: 'DB.Clients', 
    cmd: 
    { find: 'DB.Clients', 
    limit: 0, 
    skip: 0, 
    query: { '$exists': true }, 
    slaveOk: true, 
    readPreference: { preference: 'primary', tags: undefined, options: undefined } }, 
    options: 
    { skip: 0, 
    limit: 0, 
    raw: undefined, 
    hint: null, 
    timeout: undefined, 
    slaveOk: true, 
    readPreference: { preference: 'primary', tags: undefined, options: undefined }, 
    db: 
     { domain: null, 
     _events: {}, 
     _maxListeners: 10, 
     s: [Object], 
     serverConfig: [Getter], 
     bufferMaxEntries: [Getter], 
     databaseName: [Getter], 
     options: [Getter], 
     native_parser: [Getter], 
     slaveOk: [Getter], 
     writeConcern: [Getter] }, 
    disconnectHandler: { s: [Object], length: [Getter] } }, 
    topology: 
    { domain: null, 
    _events: 
     { reconnect: [Function], 
     timeout: [Object], 
     error: [Object], 
     close: [Object], 
     destroy: [Object] }, 
    _maxListeners: 10, 
    s: 
     { options: [Object], 
     callbacks: [Object], 
     logger: [Object], 
     state: 'connected', 
     reconnect: true, 
     reconnectTries: 30, 
     reconnectInterval: 1000, 
     emitError: true, 
     currentReconnectRetry: 30, 
     ismaster: [Object], 
     readPreferenceStrategies: undefined, 
     authProviders: [Object], 
     id: 5, 
     tag: undefined, 
     disconnectHandler: [Object], 
     wireProtocolHandler: {}, 
     Cursor: [Object], 
     bsonInstance: {}, 
     bson: {}, 
     pool: [Object], 
     serverDetails: [Object] }, 
    name: [Getter], 
    bson: [Getter], 
    wireProtocolHandler: [Getter], 
    id: [Getter] }, 
    cursorState: 
    { cursorId: null, 
    documents: [], 
    cursorIndex: 0, 
    dead: false, 
    killed: false, 
    init: false, 
    notified: false, 
    limit: 0, 
    skip: 0, 
    batchSize: 1000, 
    currentLimit: 0, 
    transforms: undefined }, 
    callbacks: null, 
    logger: { className: 'Cursor' }, 
    _readableState: 
    { highWaterMark: 16384, 
    buffer: [], 
    length: 0, 
    pipes: null, 
    pipesCount: 0, 
    flowing: false, 
    ended: false, 
    endEmitted: false, 
    reading: false, 
    calledRead: false, 
    sync: true, 
    needReadable: false, 
    emittedReadable: false, 
    readableListening: false, 
    objectMode: true, 
    defaultEncoding: 'utf8', 
    ranOut: false, 
    awaitDrain: 0, 
    readingMore: false, 
    decoder: null, 
    encoding: null }, 
    readable: true, 
    domain: null, 
    _events: {}, 
    _maxListeners: 10, 
    s: 
    { maxTimeMS: null, 
    numberOfRetries: 5, 
    tailableRetryInterval: 500, 
    currentNumberOfRetries: 5, 
    state: 0, 
    streamOptions: {}, 
    bson: {}, 
    ns: 'DB.Clients', 
    cmd: 
     { find: 'DB.Clients', 
     limit: 0, 
     skip: 0, 
     query: [Object], 
     slaveOk: true, 
     readPreference: [Object] }, 
    options: 
     { skip: 0, 
     limit: 0, 
     raw: undefined, 
     hint: null, 
     timeout: undefined, 
     slaveOk: true, 
     readPreference: [Object], 
     db: [Object], 
     disconnectHandler: [Object] }, 
    topology: 
     { domain: null, 
     _events: [Object], 
     _maxListeners: 10, 
     s: [Object], 
     name: [Getter], 
     bson: [Getter], 
     wireProtocolHandler: [Getter], 
     id: [Getter] }, 
    topologyOptions: 
     { socketOptions: {}, 
     auto_reconnect: true, 
     host: 'localhost', 
     port: 27017, 
     cursorFactory: [Object], 
     reconnect: true, 
     emitError: true, 
     size: 5, 
     disconnectHandler: [Object], 
     bson: {}, 
     messageHandler: [Function], 
     wireProtocolHandler: {} } }, 
    timeout: false, 
    sortValue: undefined, 
    readPreference: { preference: 'primary', tags: undefined, options: undefined } } 

而且無論是否存在與名稱的文件或不總是會返回然而,當我在命令行中運行它我得到

> db.Clients.find({Name: 'say what'}, {$exists: true}) 
{ "_id" : ObjectId("5519a66eb85de65c121182d9") } 

這表明該文件存在,如果我運行相同的cmd文件thats不在mongo它不返回任何內容。 無論如何要在退貨聲明中找到說明文件是否存在的參考?

+0

這個'({Name:msg.Name},{$ exists:true})'沒有達到您的預期。 – 2015-03-30 20:06:39

+0

嘗試使用find(...)。toArray(function(err,docs){...})',並驗證文檔的長度。我不知道這是否看起來很拙劣,但很多例子都使用這種模式。 – lxe 2015-03-30 20:06:44

回答

5

MongoDB find()方法將cursor返回到與查詢條件匹配的文檔。因此,您在console.log(doc)中看到的實際上是光標返回。當find()方法「返回文檔」時,該方法實際上是將光標返回到文檔。

您需要將toArray()方法添加到從find()方法生成的光標中,例如,

var collection = db.collection('Clients'); // get reference to the collection 
collection.find({Name: msg.Name}, {$exists: true}).toArray(function(err, doc) //find if a value exists 
{  
    if(doc) //if it does 
    { 
     console.log(doc); // print out what it sends back 
    } 
    else if(!doc) // if it does not 
    { 
     console.log("Not in docs"); 
    } 
}); 

toArray()方法返回一個數組,其中包含遊標的所有文檔。該方法完全遍歷遊標,將所有文檔加載到RAM中並耗盡遊標。