简体   繁体   中英

MongoDB findOne query doesn't return result or undefined

I'm new to node.js and mongo, and I'm trying to use findOne() to retrieve an object from the "quizzes" collection of my database so that I can examine its properties.

I know that the object exists, because in the Mongo shell, a findOne() call gives me this:

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

In my routes/index.js, I have this:

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

A console.log(quizCollection) gives:

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

while a console.log(quiz) gives:

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

and of course, trying to reference any property of quiz (ex. quiz('quiz_id') ) is undefined.

quizCollection.insert() seems to successfully insert an object, so I think I'm getting the right collection. I thought findOne() would return either undefined if it didn't find anything, or an object that fits the criteria, but what I'm printing doesn't seem to be either. How can I retrieve an object?

NodeJS is asynchronous. Some APIs are synchronous, but findOne is an asynchronous one.

findOne has as no return value. You'll get the result passed on your callback. Most APIs return an error as the first argument, which would be undefined if there wasn't an error, and the result of your query/ fs operation/ net operation etc.

Example: quiz.findOne({quiz_id: 1}, function (err, quiz) {});

This test shows how to query. here

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