简体   繁体   中英

mongodb check to see if values exist(node.js)

Im using Node.js and Mongo(mongodb driver) to add items to a collection. I have a html site that passes informtion to the page using socket.io. I can insert into the db but when I try to see if a value exists I get an odd return from Mongo. I send over a name and try to put it in the clients collection. What i have so far is:

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

            }
}

This returns me :

{ 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 } }

And will always return regardless of whether there is a document with the name or not yet when I run it in the cli I get

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

This shows that the document is present and if I run the same cmd for a document thats not in mongo it returns nothing. Is there anyway to find a reference in the return statement that states whether the document is there or not?

MongoDB find() method returns a cursor to the documents that match the query criteria. So what you see in the console.log(doc) is actually the cursor returned. When the find() method “returns documents,” the method is actually returning a cursor to the documents.

You need to add a toArray() method to the resulting cursor from the find() method, eg

var collection = db.collection('Clients');  // get reference to the collection
collection.find({Name: msg.Name}, {$exists: true}).toArray(function(err, docs) //find if documents that satisfy the criteria exist
{     
    if(docs.length > 0) //if exists
    {
        console.log(docs); // print out what it sends back
    }
    else // if it does not 
    {
        console.log("Not in docs");
    }
});

The toArray() method returns an array that contains all the documents from a cursor. The method iterates completely the cursor, loading all the documents into RAM and exhausting the cursor.

Edit: docs is an array of length 0. So check length of array instead

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