Mongoose find(),如何访问结果文件?

我刚刚开始玩mongoose和孟戈。 我有以下代码:

var ninjaSchema = mongoose.Schema({ name: String, skill: Number }); var Ninja = mongoose.model('Ninja',ninjaSchema); module.exports = { init : function(){ console.log('Connecting to database'); mongoose.connect('mongodb://localhost/mydb'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { console.log('Successfully connected!'); }); }, createNinja : function(name,skill){ var n = new Ninja({name:name,skill:skill}); n.save(function(err,n){ if (err) console.log('saving failed'); console.log('saved '+ n.name); }); }, getNinjas : function(){ var res = null; res = Ninja.findOne({},'name skill',function(err,docs){ if (err) console.log('error occured in the query'); return 'ninja name: '+docs.name+' ninja skill: '+docs.skill; }); return res; } 

将条目添加到数据库没有问题,但是我在检索它们时遇到问题。 我对整个事情是如何工作感到困惑。 我的理解如下:

有架构,就像在oop类,所以只是在数据库中的logging的蓝图。 该模型是一个logging,好吧,也许多一点,因为我看到你可以添加一个方法到模型中。 那么…我真的不明白如何使用它们。 你能给我一个线索是什么吗?

回到主题:当发出find命令时,它会调用匿名函数,文档应该是正确的结果? 现在我该如何访问它们? 从现在开始,如果我loginres,我会得到以下内容:

 { options: {}, safe: undefined, _conditions: {}, _updateArg: {}, _fields: { name: 1, skill: 1 }, _geoComparison: undefined, op: 'findOne', model: { [Function: model] base: { connections: [Object], plugins: [], models: [Object], modelSchemas: [Object], options: {} }, modelName: 'Ninja', model: [Function: model], db: { base: [Object], collections: [Object], models: {}, replica: false, hosts: null, host: 'localhost', port: 27017, user: undefined, pass: undefined, name: 'mydb', options: [Object], _readyState: 1, _closeCalled: false, _hasOpened: true, _listening: true, _events: [Object], db: [Object] }, schema: { paths: [Object], subpaths: {}, virtuals: [Object], nested: {}, inherits: {}, callQueue: [], _indexes: [], methods: {}, statics: {}, tree: [Object], _requiredpaths: [], options: [Object], _events: {} }, options: undefined, collection: { collection: [Object], opts: [Object], name: 'ninjas', conn: [Object], queue: [], buffer: false } } } 

另外如果我使用Ninja.find(...,function(err,docs){ ... })我该如何去通过文档? 或者我如何检索我的logging?

我find了错。 这更多的是一个概念:我正在处理asynchronous调用,并试图从另一个函数返回结果,不知道什么时候会执行。 所以会发生什么是我请求执行数据库查询并返回结果,结果是null。 此代码:

 getNinjas : function(){ var res = null; Ninja.find({},'name skill',function(err,docs){ if (err) console.log('error occured in the database'); console.log(docs); }); return res; } 

返回null,但是! console.log(文档)打印到控制台从数据库中的所有值,我正在尝试做什么。 现在我需要做出改变,很可能会传递一个callback,在接收结果时执行callback。

随着更改代码如下所示:

 getNinjas : function(res){ var twisted = function(res){ return function(err, data){ if (err){ console.log('error occured'); return; } res.send('My ninjas are:\n'); console.log(data); } } Ninja.find({},'name skill',twisted(res)); } 

所以像这样我能够传递响应对象,所以我可以发送我的忍者的名字:)