Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript mongodb检查是否存在值(node.js)_Javascript_Node.js_Mongodb - Fatal编程技术网

Javascript mongodb检查是否存在值(node.js)

Javascript mongodb检查是否存在值(node.js),javascript,node.js,mongodb,Javascript,Node.js,Mongodb,Im使用Node.js和Mongo(mongodb驱动程序)将项目添加到集合中。 我有一个html站点,它使用socket.io将信息传递到页面。我可以插入到数据库中,但当我尝试查看是否存在值时,我从Mongo得到一个奇数返回。我发送了一个名字,并试图把它放在客户集合中。 到目前为止,我得到的是: socket.on('DB', function(msg) { if(msg.Status == "Read") { MongoClie

Im使用Node.js和Mongo(mongodb驱动程序)将项目添加到集合中。 我有一个html站点,它使用socket.io将信息传递到页面。我可以插入到数据库中,但当我尝试查看是否存在值时,我从Mongo得到一个奇数返回。我发送了一个名字,并试图把它放在客户集合中。 到目前为止,我得到的是:

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 } }
在我获取的cli中运行文档时,无论是否存在具有该名称的文档,都将始终返回

> db.Clients.find({Name: 'say what'}, {$exists: true})
{ "_id" : ObjectId("5519a66eb85de65c121182d9") }
这表明文档存在,如果我对不在mongo中的文档运行相同的cmd,它将不返回任何内容。 是否仍要在return语句中找到一个引用来说明文档是否存在?

MongoDB方法将a返回到与查询条件匹配的文档。因此,您在
console.log(doc)
中看到的实际上是返回的光标。当
find()
方法“返回文档”时,该方法实际上是将光标返回到文档

您需要从
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");
    }
});
该方法返回一个数组,其中包含游标中的所有文档。该方法完全迭代游标,将所有文档加载到RAM中并耗尽游标。

({Name:msg.Name},{$exists:true})
未达到预期效果。请尝试使用
查找(…).toArray(函数(err,docs){…})
,并验证文档的长度。我不知道这是否有问题,但很多例子都在使用这种模式。