0

所以我有这个脚本:

var db = require('mongoskin').db('localhost:27017/titles', {safe:true});
var titles = db.collection('titles');

title = titles.findOne(function(err, result){
if (err) throw err;
return result.title;
});

console.log(title)

集合中的这个 BSON 对象:

{"title": "Hello World", "postNumber": 0, "_id": ObjectId("509eeffbf8f11e8813000001")}

我的目标是让字符串“Hello World”输出到控制台,但我得到了这个:

{ emitter: { _events: { open: [Object] }, _maxListeners: 50 },
  state: 1,
  options: undefined,
  skinDb:
   { emitter: { _events: [Object], _maxListeners: 100 },
     state: 1,
     _dbconn:
      { databaseName: 'titles',
    serverConfig: [Object],
    options: [Object],
    _applicationClosed: false,
    native_parser: true,
    bsonLib: [Object],
    bson: {},
    bson_deserializer: [Object],
    bson_serializer: [Object],
    _state: 'connecting',
    pkFactory: [Object],
    forceServerObjectId: false,
    safe: true,
    notReplied: {},
    isInitializing: true,
    auths: [],
    openCalled: true,
    commands: [],
    _callBackStore: [Object],
    logger: [Object],
    slaveOk: false,
    tag: 1352682584657,
    eventHandlers: [Object],
    serializeFunctions: false,
    raw: false,
    recordQueryStats: false,
    reaperEnabled: false,
    _lastReaperTimestamp: 1352682584657,
    retryMiliSeconds: 1000,
    numberOfRetries: 60,
    reaperInterval: 10000,
    reaperTimeout: 30000,
    readPreference: undefined },
 db: null,
 username: '',
 password: undefined,
 admin: { emitter: {}, state: 0, skinDb: [Circular], admin: null },
 _collections: { titles: [Circular] },
 bson_serializer:
  { 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] },
 ObjectID:
  { [Function: ObjectID]
    index: 0,
    createPk: [Function: createPk],
    createFromTime: [Function: createFromTime],
    createFromHexString: [Function: createFromHexString] } },
  ObjectID:
   { [Function: ObjectID]
 index: 0,
 createPk: [Function: createPk],
 createFromTime: [Function: createFromTime],
 createFromHexString: [Function: createFromHexString] },
  collectionName: 'titles',
  collection: null,
  internalHint: null,
  hint: [Getter/Setter] }

当我将 console.log() 放在函数中时它工作得很好,但由于某种原因我无法返回字符串。

解决了:

read = function(callback){
    titles.findOne(function(err, result){
        if (err) throw err;
        callback(result.title);
    });
};

read(function(title){
console.log(title);
});
4

1 回答 1

0

你需要了解javascript回调。

1 - findOne 将返回一个 db 对象,而不是您的字符串的结果。我从未读过 mongoskin doco,但我认为它将是一个数据库集合或某种你在 console.log 打印输出中看到的东西。2 - 在回调中你确实返回 result.title; 永远不会像您期望的那样返回标题。所以这就是为什么我建议阅读一下回调是如何工作的。

正如您提到的,打印标题的正确方法是将 console.log 放在回调函数中。

于 2012-11-12T06:17:44.313 回答