节点js和mongodb找到

时间:2014-11-16 15:50:00

标签: node.js mongodb

我使用此代码连接到我的mongo db localhost并找到“名称”,但我在consol.log中遇到问题:

url = require("url"),
emitter = require("events").EventEmitter,
assert = require("assert"),

mongo = require("mongodb"),
Cursor = mongo.Cursor;

var uristring = "mongodb://localhost:27017/test"; 
var mongoUrl = url.parse (uristring);


mongo.MongoClient.connect (uristring, function (err, db) { 
    var test = db.collection ("test")
        console.log ("Success connecting to " + mongoUrl.protocol + "//" + mongoUrl.hostname + ".");

        console.log (test.find({},{name:1,_id:0}));
    db.close();
});

当我在mongo的终端中使用db.test.find({},{name:1,_id:0})时返回{ "name" : "pooya" } 但在nodjs代码中它返回:

Success connecting to mongodb://localhost.
{ db: 
   { domain: null,
     _events: {},
     _maxListeners: 10,
     databaseName: 'test',
     serverConfig: 
      { domain: null,
        _events: {},
        _maxListeners: 10,
        _callBackStore: [Object],
        _commandsStore: [Object],
        auth: [Object],
        _dbStore: [Object],
        host: 'localhost',
        port: 27017,
        options: [Object],
        internalMaster: true,
        connected: true,
        poolSize: 5,
        disableDriverBSONSizeCheck: false,
        _used: true,
        replicasetInstance: null,
        emitOpen: false,
        ssl: false,
        sslValidate: false,
        sslCA: null,
        sslCert: undefined,
        sslKey: undefined,
        sslPass: undefined,
        serverCapabilities: [Object],
        name: 'localhost:27017',
        socketOptions: [Object],
        logger: [Object],
        eventHandlers: [Object],
        _serverState: 'connected',
        _state: [Object],
        recordQueryStats: false,
        socketTimeoutMS: [Getter/Setter],
        _readPreference: [Object],
        db: [Circular],
        dbInstances: [Object],
        connectionPool: [Object],
        isMasterDoc: [Object] },
     options: 
      { read_preference_tags: null,
        read_preference: 'primary',
        url: 'mongodb://localhost:27017/test',
        native_parser: true,
        readPreference: [Object],
        safe: false,
        w: 1 },
     _applicationClosed: false,
     slaveOk: false,
     bufferMaxEntries: -1,
     native_parser: true,
     bsonLib: 
      { BSON: [Object],
        Long: [Object],
        ObjectID: [Object],
        DBRef: [Function: DBRef],
        Code: [Function: Code],
        Timestamp: [Object],
        Binary: [Object],
        Double: [Function: Double],
        MaxKey: [Function: MaxKey],
        MinKey: [Function: MinKey],
        Symbol: [Function: Symbol] },
     bson: { promoteLongs: true },
     bson_deserializer: 
      { Code: [Function: Code],
        Symbol: [Function: Symbol],
        BSON: [Object],
        DBRef: [Function: DBRef],
        Binary: [Object],
        ObjectID: [Object],
        Long: [Object],
        Timestamp: [Object],
        Double: [Function: Double],
        MinKey: [Function: MinKey],
        MaxKey: [Function: MaxKey],
        promoteLongs: true },
     bson_serializer: 
      { Code: [Function: Code],
        Symbol: [Function: Symbol],
        BSON: [Object],
        DBRef: [Function: DBRef],
        Binary: [Object],
        ObjectID: [Object],
        Long: [Object],
        Timestamp: [Object],
        Double: [Function: Double],
        MinKey: [Function: MinKey],
        MaxKey: [Function: MaxKey],
        promoteLongs: true },
     _state: 'connected',
     pkFactory: 
      { [Function: ObjectID]
        index: 2954887,
        createPk: [Function: createPk],
        createFromTime: [Function: createFromTime],
        createFromHexString: [Function: createFromHexString],
        isValid: [Function: isValid] },
     forceServerObjectId: false,
     safe: false,
     notReplied: {},
     isInitializing: true,
     openCalled: true,
     commands: [],
     logger: { error: [Function], log: [Function], debug: [Function] },
     tag: 1416152062206,
     eventHandlers: 
      { error: [],
        parseError: [],
        poolReady: [],
        message: [],
        close: [] },
     serializeFunctions: false,
     raw: false,
     recordQueryStats: false,
     retryMiliSeconds: 1000,
     numberOfRetries: 60,
     readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined } },
  collection: 
   { db: 
      { domain: null,
        _events: {},
        _maxListeners: 10,
        databaseName: 'test',
        serverConfig: [Object],
        options: [Object],
        _applicationClosed: false,
        slaveOk: false,
        bufferMaxEntries: -1,
        native_parser: true,
        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: 1416152062206,
        eventHandlers: [Object],
        serializeFunctions: false,
        raw: false,
        recordQueryStats: false,
        retryMiliSeconds: 1000,
        numberOfRetries: 60,
        readPreference: [Object] },
     collectionName: 'test',
     internalHint: null,
     opts: {},
     slaveOk: false,
     serializeFunctions: false,
     raw: false,
     readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined },
     pkFactory: 
      { [Function: ObjectID]
        index: 2954887,
        createPk: [Function: createPk],
        createFromTime: [Function: createFromTime],
        createFromHexString: [Function: createFromHexString],
        isValid: [Function: isValid] },
     serverCapabilities: undefined },
  selector: {},
  fields: { name: 1, _id: 0 },
  skipValue: 0,
  limitValue: 0,
  sortValue: undefined,
  hint: null,
  explainValue: undefined,
  snapshot: undefined,
  timeout: true,
  tailable: undefined,
  awaitdata: undefined,
  oplogReplay: undefined,
  numberOfRetries: 5,
  currentNumberOfRetries: 5,
  batchSizeValue: 0,
  raw: false,
  readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined },
  returnKey: undefined,
  maxScan: undefined,
  min: undefined,
  max: undefined,
  showDiskLoc: undefined,
  comment: undefined,
  tailableRetryInterval: 100,
  exhaust: false,
  partial: false,
  slaveOk: false,
  maxTimeMSValue: undefined,
  connection: undefined,
  totalNumberOfRecords: 0,
  items: [],
  cursorId: { _bsontype: 'Long', low_: 0, high_: 0 },
  dbName: undefined,
  state: 0,
  queryRun: false,
  getMoreTimer: false,
  collectionName: 'test.test' }

为什么会发生这种情况?如何解决?

1 个答案:

答案 0 :(得分:2)

欢迎使用StackOverflow。

您错误地使用了API。如果您是node.js的新手,MongoDB驱动程序通过回调异步返回查询结果,而不是像您目前可能遇到的大多数语言那样同步。

所以,基本上你是这样做的

var results = test.find({},{name:1,_id:0})
console.log (results);

但你真正想做的是:

 test.find({name:1,_id:0}, new function(error, results)
  {
    if(error! = null) console.log(error);
    else //do whatever you want with the results
  });

请注意,test.find()之后的代码将独立于查询及其结果而继续运行。查询完成后将调用结果处理。 顺便说一句。我还认为传递给find()方法的参数有点错误。查询应该是第一个参数,在您的示例中,它是第二个参数,如果我没有弄错的话。该方法如下所示:find(query[, options], callback)

您可以找到MongoDB驱动程序here的文档,包括find方法。

您应该使用find()方法或多或少地使用connect()方法执行相同的操作,在该方法中,您正在编写查询的回调。

如果您对异步,事件驱动或非阻塞编程的概念不满意,请考虑阅读以下链接:

http://book.mixu.net/node/ch7.html

http://justinklemm.com/node-js-async-tutorial/

编辑:

抱歉,我必须自己编辑。回调有两个参数,第一个是错误,第二个是结果。 Haven暂时没有使用它。

相关问题