所以我有这个脚本:
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);
});
答案 0 :(得分:0)
你需要了解javascript回调。
1 - findOne将返回一个db对象,而不是字符串的结果。我从来没有读过mongoskin doco,但我认为这将是一个db集合或某种类型,你在console.log打印出来。 2 - 在回调中你做返回result.title;永远不会像你期望的那样返回标题。所以这就是为什么我建议阅读回调如何工作的原因。
打印标题的正确方法是将console.log放在回调函数中,如你所说。