通过键名mongodb node.js驱动程序获取值

时间:2015-11-02 04:27:30

标签: javascript node.js mongodb

我已经查看了所有位置,无法找到是否可以完成我试图仅通过搜索其关键名称来返回对象中的所有值。我的文档看起来像这样。

{
    "_id": ObjectID("5636e00c09431db4560ef063"),
    "username": "example@web.com",
    "credentials": {
        "password": "e5e0ba4ce8ae13d1d0291e98d9a62b4d68f1db737a36a9373f916185157500cc",
        "randomSalt": "00dfb37635ba7e5a513f9fd6e8bdf746f85ec3571df8288e1fdb44f399e331f0"
    }
}

使用本机node.js驱动程序执行此操作是否有一种快速简便的方法

到目前为止我的代码

function getUserLoginFromDatabase(username, callback) {
    mongodb.connect(url, function(err, db) {
        if(err) {
                callback(err);
                db.close();
                return;
            }

        var collection = db.collection(username);

        collection.find({},{"credentials":1}, function(err, result) {
            console.log(result);
            callback(err, result);
            db.close();
        });
    });
};

更新 关于Alok Deshwal说要做的事情,我得到了这个。我正在使用mongodb v3.0.7,如果这有所不同。

function getUserLoginFromDatabase(username, callback) {
    mongodb.connect(url, function(err, db) {
        if(err) {
                callback(err);
                db.close();
                return;
            }

        var collection = db.collection(username);

        collection.find({},{"credentials":1,"_id":0,"username":0}, function(err, result) {
            console.log(result);
            callback(err, result);
            db.close();
        });
    });
};

输出

Readable {                                                                                                                                           
  connection: null,                                                                                                                                  
  server: null,                                                                                                                                      
  disconnectHandler:                                                                                                                                 
   { s: { storedOps: [], storeOptions: [Object], topology: [Object] },                                                                               
     length: [Getter] },                                                                                                                             
  bson: {},                                                                                                                                          
  ns: 'mydb.exsample@web.com',                                                                                                                                
  cmd:                                                                                                                                               
   { find: 'mydb.exsample@web.com',                                                                                                                           
     limit: 0,                                                                                                                                       
     skip: 0,                                                                                                                                        
     query: {},                                                                                                                                      
     slaveOk: true,                                                                                                                                  
     readPreference: { preference: 'primary', tags: undefined, options: undefined },                                                                 
     fields: { credentials: 1, _id: 0, username: 0 } },                                                                                              
  options:                                                                                                                                           
   { skip: 0,                                                                                                                                        
     limit: 0,                                                                                                                                       
     raw: undefined,                                                                                                                                 
     hint: null,                                                                                                                                     
     timeout: undefined,                                                                                                                             
     slaveOk: true,                                                                                                                                  
     readPreference: { preference: 'primary', tags: undefined, options: undefined },                                                                 
     db:                                                                                                                                             
      EventEmitter {                                                                                                                                 
        domain: null,                                                                                                                                
        _events: {},                                                                                                                                 
        _eventsCount: 0,                                                                                                                             
        _maxListeners: undefined,                                                                                                                    
        s: [Object],                                                                                                                                 
        serverConfig: [Getter],                                                                                                                      
        bufferMaxEntries: [Getter],                                                                                                                  
        databaseName: [Getter],                                                                                                                      
        options: [Getter],                                                                                                                           
        native_parser: [Getter],                                                                                                                     
        slaveOk: [Getter],                                                                                                                           
        writeConcern: [Getter] },                                                                                                                    
     promiseLibrary: [Function: Promise],                                                                                                            
     disconnectHandler: { s: [Object], length: [Getter] } },                                                                                         
  topology:                                                                                                                                          
   EventEmitter {                                                                                                                                    
     domain: null,                                                                                                                                   
     _events:                                                                                                                                        
      { reconnect: [Function],                                                                                                                       
        timeout: [Object],                                                                                                                           
        error: [Object],                                                                                                                             
        close: [Function],                                                                                                                           
        destroy: [Object] },                                                                                                                         
     _eventsCount: 5,                                                                                                                                
     _maxListeners: undefined,                                                                                                                       
     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: 1,                                                                                                                                       
        tag: undefined,                                                                                                                              
        disconnectHandler: [Object],                                                                                                                 
        wireProtocolHandler: {},                                                                                                                     
        Cursor: [Object],                                                                                                                            
        bsonInstance: {},                                                                                                                            
        bson: {},                                                                                                                                    
        pool: [Object],                                                                                                                              
        serverDetails: [Object] },                                                                                                                   
     name: [Getter],                                                                                                                                 
     bson: [Getter],                                                                                                                                 
     wireProtocolHandler: [Getter],                                                                                                                  
     id: [Getter] },                                                                                                                                 
  cursorState:                                                                                                                                       
   { cursorId: null,                                                                                                                                 
     cmd:                                                                                                                                            
      { find: 'mydb.exsample@web.com',                                                                                                                        
        limit: 0,                                                                                                                                    
        skip: 0,                                                                                                                                     
        query: {},                                                                                                                                   
        slaveOk: true,                                                                                                                               
        readPreference: [Object],                                                                                                                    
        fields: [Object] },                                                                                                                          
     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:                                                                                                                                    
   ReadableState {                                                                                                                                   
     objectMode: true,                                                                                                                               
     highWaterMark: 16,                                                                                                                              
     buffer: [],                                                                                                                                     
     length: 0,                                                                                                                                      
     pipes: null,                                                                                                                                    
     pipesCount: 0,                                                                                                                                  
     flowing: null,                                                                                                                                  
     ended: false,                                                                                                                                   
     endEmitted: false,                                                                                                                              
     reading: false,                                                                                                                                 
     sync: true,                                                                                                                                     
     needReadable: false,                                                                                                                            
     emittedReadable: false,                                                                                                                         
     readableListening: false,                                                                                                                       
     defaultEncoding: 'utf8',                                                                                                                        
     ranOut: false,                                                                                                                                  
     awaitDrain: 0,                                                                                                                                  
     readingMore: false,                                                                                                                             
     decoder: null,                                                                                                                                  
     encoding: null },                                                                                                                               
  readable: true,                                                                                                                                    
  domain: null,                                                                                                                                      
  _events: {},                                                                                                                                       
  _eventsCount: 0,                                                                                                                                   
  _maxListeners: undefined,                                                                                                                          
  s:                                                                                                                                                 
   { numberOfRetries: 5,                                                                                                                             
     tailableRetryInterval: 500,                                                                                                                     
     currentNumberOfRetries: 5,                                                                                                                      
     state: 0,                                                                                                                                       
     streamOptions: {},                                                                                                                              
     bson: {},                                                                                                                                       
     ns: 'mydb.exsample@web.com',                                                                                                                             
     cmd:                                                                                                                                            
      { find: 'mydb.exsample@web.com',                                                                                                                        
        limit: 0,                                                                                                                                    
        skip: 0,                                                                                                                                     
        query: {},                                                                                                                                   
        slaveOk: true,                                                                                                                               
        readPreference: [Object],                                                                                                                    
        fields: [Object] },                                                                                                                          
     options:                                                                                                                                        
      { skip: 0,                                                                                                                                     
        limit: 0,                                                                                                                                    
        raw: undefined,                                                                                                                              
        hint: null,                                                                                                                                  
        timeout: undefined,                                                                                                                          
        slaveOk: true,                                                                                                                               
        readPreference: [Object],                                                                                                                    
        db: [Object],                                                                                                                                
        promiseLibrary: [Function: Promise],                                                                                                         
        disconnectHandler: [Object] },                                                                                                               
     topology:                                                                                                                                       
      EventEmitter {                                                                                                                                 
        domain: null,                                                                                                                                
        _events: [Object],                                                                                                                           
        _eventsCount: 5,                                                                                                                             
        _maxListeners: undefined,                                                                                                                    
        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: {} },                                                                                                                   
     promiseLibrary: [Function: Promise],                                                                                                            
     currentDoc: null },                                                                                                                             
  timeout: false,                                                                                                                                    
  sortValue: undefined,                                                                                                                              
  readPreference: { preference: 'primary', tags: undefined, options: undefined } }

3 个答案:

答案 0 :(得分:0)

您可以执行以下操作,以便仅获取现有凭据。

var res = []; db.collection.find({credentials : {$exists:true}}).forEach(function(document){ res.push(document.credentials})

然后你可以回调数组: callback(err, res)

这对你有帮助吗?

答案 1 :(得分:0)

好吧,基于我最初的想法是正确的方式,我可以通过将其投入数组来实现我的输出。您只需 "credentials":1 即可获取凭据,并且包含 "credentials":1,"_id":0,"username":0 ,如Alok Deshwal所述,会导致mongodb抛出错误。

function getUserLoginFromDatabase(username, callback) {
    mongodb.connect(url, function(err, db) {
        if(err) {
                callback(err);
                db.close();
                return;
            }

        var collection = db.collection(username);

        collection.find({},{"credentials":1}).toArray(function(err, result) {
            callback(err, result);
            db.close();
        });
    });
};

但是在回调中使用数据变得乏味,因为它不应该在数组中。我将问另外一个问题,以及为什么包含更多字段会导致mongodb抛出错误。

randomSalt = result[0]["credentials"].randomSalt;
userStoredPassword = result[0]["credentials"].password;

此答案的结论是here

答案 2 :(得分:-1)

如果要按密钥名称搜索,可以使用$ exists operator

db.collection.find({},{"credentials":1,"_id":0,"username":0})

使用"keyname":0从结果中排除,"keyname":1包含在结果