2014-11-16 3 views
0

내가 내 몽고 DB를 로컬 호스트에 연결하고 "이름"을 찾으려면이 코드를 사용하지만 난 consol.log에서 문제가 발견 몽고 년은 { "name" : "pooya" } 를 반환하지만 nodjs 코드에 반환 :nodejs와 몽고 DB

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

왜 그 일이 어떻게 그것을 해결하기 위해?

답변

2

Welcome to StackOverflow.

API를 잘못 사용하고 있습니다. MongoDB 드라이버는 콜백을 통해 쿼리 결과를 비동기 적으로 반환하지만, node.js를 처음 사용하는 경우에는 지금까지 만난 적이있는 대부분의 언어와 동 기적으로 유사하지는 않습니다. 명심

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() 후 코드는 독립적으로 쿼리의 실행 유지하고 것 :

그래서

, 기본적으로이

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

하지만 당신이 정말로 원하는 것은을하고있다 그 결과. 결과 처리는 조회가 완료 될 때 호출됩니다. Btw. 나는 또한 귀하의 find() 메서드에 전달 된 매개 변수가 어떻게 든 잘못되었다고 생각합니다. 쿼리는 첫 번째 매개 변수 여야하며 실수로 입력하지 않은 경우에는 두 번째 매개 변수입니다. 이 메서드는 다음과 같습니다 : find(query[, options], callback).

find 방법을 포함하여 MongoDB 드라이버 here의 설명서를 찾을 수 있습니다.

connect() 메서드를 사용했을 때와 마찬가지로 쿼리를 작성하는 경우와 동일하게 find() 메서드를 사용하여 동일하게 처리해야합니다.

당신이 또는 비 차단 프로그램이 링크 읽는 고려하시기 바랍니다 구동 비동기 이벤트의 개념이 어려우면 : http://book.mixu.net/node/ch7.html

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

편집 :

죄송합니다, 나 자신을 편집해야합니다. 콜백에는 두 개의 매개 변수가 있으며, 첫 번째는 오류이고 SECOND는 결과입니다. 잠시 사용하지 않았습니다.

는 그런 일처럼 비 차단 너무
+0

하지만 정의되지 않은 반환 mongo.MongoClient.connect (uristring, 기능 (ERR, dB) { \t \t db.collection ("테스트", 기능 (모음) {\t console.log ("+ mongoUrl.protocol +"// "mongoUrl.hostname +". ")";에 연결 성공. \t \t collection.find ({}, {이름 : 1, _id : 0 }, 함수 (결과) \t \t { \t \t \t 콘솔.로그 (결과); \t \t \t db.close(); \t \t}); \t}); }}); – pofa

+0

앞서 말했듯이, 당신은 또한'collection.find()'메소드를 잘못 사용하고 있습니다. 그것은'collection.find ({name : 1, _id : 0}, 새로운 함수 ...)'이어야합니다. 명백한 이유없이 첫 번째 매개 변수를 건너 뜁니다. 두 번째 매개 변수는'explain','limit's,'timeout'과 같은 질의 옵션입니다. 콜백의 첫 번째 매개 변수는 쿼리에서 실패를보고 할 수있는 오류 객체입니다. 따라서 콜백은 새로운 함수 (오류, 결과)처럼 보일 수 있습니다. 자세한 내용은 오류를 확인할 수 있습니다. –

+0

답변을 다시 확인하십시오, 나는 실수를했고 지금 바로 수정했습니다. –