MongoDB findOne查询没有返回结果或未定义

时间:2015-05-26 21:03:34

标签: javascript node.js mongodb

我是node.js和mongo的新手,我尝试使用findOne()从"测验"中检索对象。收集我的数据库,以便我可以检查它的属性。

我知道对象存在,因为在Mongo shell中,findOne()调用给了我这个:

> db.quizzes.findOne({ quiz_id:1 })
{
    "_id" : ObjectId("5564b0bf28b816e2462b6a1a"),
    "quiz_id" : 1
 }

在我的routes / index.js中,我有这个:

router.post('/submitanswer', function(req, res) {
    var db = req.db;
    var quizCollection = db.get('quizzes');
    var quiz = quizCollection.findOne({ quiz_id: 1 });
}

console.log(quizCollection)给出:

{ manager: 
   { driver: 
      { _construct_args: [],
        _native: [Object],
        _emitter: [Object],
        _state: 2,
        _connect_args: [Object] },
     helper: { toObjectID: [Function], isObjectID: [Function], id: [Object] },
     collections: { quizzes: [Circular] },
     options: { safe: true },
     _events: {} },
  driver: 
   { _construct_args: [],
     _native: 
      { domain: null,
        _events: {},
        _maxListeners: undefined,
        databaseName: 'quizzr',
        serverConfig: [Object],
        options: [Object],
        _applicationClosed: false,
        slaveOk: false,
        bufferMaxEntries: -1,
        native_parser: false,
        bsonLib: [Object],
        bson: [Object],
        bson_deserializer: [Object],
        bson_serializer: [Object],
        _state: 'connected',
        pkFactory: [Object],
        forceServerObjectId: false,
        safe: false,
        notReplied: {},
        isInitializing: true,
        openCalled: true,
        commands: [],
        logger: [Object],
        tag: 1432673566484,
        eventHandlers: [Object],
        serializeFunctions: false,
        raw: false,
        recordQueryStats: false,
        retryMiliSeconds: 1000,
        numberOfRetries: 60,
        readPreference: [Object] },
     _emitter: { domain: null, _events: {}, _maxListeners: 50 },
     _state: 2,
     _connect_args: [ 'mongodb://localhost:27017/quizzr', [Object] ] },
  helper: 
   { toObjectID: [Function],
     isObjectID: [Function],
     id: 
      { [Function: ObjectID]
        index: 847086,
        createPk: [Function: createPk],
        createFromTime: [Function: createFromTime],
        createFromHexString: [Function: createFromHexString],
        isValid: [Function: isValid],
        ObjectID: [Circular],
        ObjectId: [Circular] } },
  name: 'quizzes',
  col: 
   { _construct_args: [],
     _native: 
      { db: [Object],
        collectionName: 'quizzes',
        internalHint: null,
        opts: {},
        slaveOk: false,
        serializeFunctions: false,
        raw: false,
        readPreference: [Object],
        pkFactory: [Object],
        serverCapabilities: undefined },
     _emitter: { domain: null, _events: {}, _maxListeners: Infinity },
     _state: 2,
     _skin_db: 
      { _construct_args: [],
        _native: [Object],
        _emitter: [Object],
        _state: 2,
        _connect_args: [Object] },
     _collection_args: [ 'quizzes', undefined ],
     id: 
      { [Function: ObjectID]
        index: 847086,
        createPk: [Function: createPk],
        createFromTime: [Function: createFromTime],
        createFromHexString: [Function: createFromHexString],
        isValid: [Function: isValid],
        ObjectID: [Circular],
        ObjectId: [Circular] },
     emitter: { domain: null, _events: {}, _maxListeners: Infinity } },
  options: {} }

console.log(quiz)给出:

{ col: 
   { manager: 
      { driver: [Object],
        helper: [Object],
        collections: [Object],
        options: [Object],
        _events: {} },
     driver: 
      { _construct_args: [],
        _native: [Object],
        _emitter: [Object],
        _state: 2,
        _connect_args: [Object] },
     helper: { toObjectID: [Function], isObjectID: [Function], id: [Object] },
     name: 'quizzes',
     col: 
      { _construct_args: [],
        _native: [Object],
        _emitter: [Object],
        _state: 2,
        _skin_db: [Object],
        _collection_args: [Object],
        id: [Object],
        emitter: [Object] },
     options: {} },
  type: 'findOne',
  opts: { quiz_id: 1, name: 1, fields: {}, safe: true },
  domain: null,
  _events: { error: [Function], success: [Function] },
  _maxListeners: undefined,
  emitted: {},
  ended: false,
  success: [Function],
  error: [Function],
  complete: [Function],
  resolve: [Function],
  fulfill: [Function],
  reject: [Function],
  query: { quiz_id: 1 } }

当然,尝试引用测验的任何属性(例如quiz('quiz_id'))都是未定义的。

quizCollection.insert()似乎成功插入了一个对象,所以我想我得到了正确的集合。我认为findOne()如果没有找到任何内容,或者符合标准的对象,将返回未定义的内容,但我打印的内容似乎也不是。如何检索对象?

1 个答案:

答案 0 :(得分:1)

NodeJS是异步的。某些API是同步的,但findOne是异步的。

findOne没有返回值。您将在回调中获得结果。大多数API都会返回错误作为第一个参数,如果没有错误,则会返回未定义的错误,以及查询/ fs操作/网络操作的结果等。

实施例: quiz.findOne({quiz_id: 1}, function (err, quiz) {});

此测试显示如何查询。 here