所以我有这个脚本:
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);
});