Meteor无法从MongoDB中检索数据
非常简单,没有任何configuration – >
在项目目录中我input了命令:
$ meteor mongo
来访问的MongoDB
从那里(mongo shell),我切换到db meteor使用命令use meteor
然后input一些基本的数据来testing:
j = { name: "mongo" } k = { x: 3 } db.testData.insert(j) db.testData.insert(k)
我检查并得到了结果input: db.testData.find()
这是我的meteor代码,只要在客户端上需要mongodb访问:
if (Meteor.isClient) { Template.hello.greeting = function () { return "Welcome to test."; }; Template.hello.events({ 'click input' : function () { // template data, if any, is available in 'this' if (typeof console !== 'undefined') console.log("You pressed the button"); } }); Documents = new Meteor.Collection('testData'); var document = Documents.find(); console.log(document); var documentCbResults = Documents.find(function(err, items) { console.log(err); console.log(items); }); }
在检查浏览器和基于日志,它说undefined
。 从mongodb中检索数据并显示到客户端控制台,我没有成功。
我错过了什么?
只在客户端定义集合是不够的。 您的mongo数据库驻留在服务器上,您的客户端需要从某个地方获取数据。 它不直接从mongodb(我认为),但通过与服务器上的集合同步获取它。
在客户端和服务器的联合范围内定义Documents
集合。 您可能还需要等待Documents
订阅才能完成内容。 更安全的是:
Meteor.subscribe('testData', function() { var document = Documents.find(); console.log(document); });
对于这个答案,我将假设这是一个新创build的项目,仍然是自动发布的。
正如Christian指出的那样,您需要在客户端和服务器上定义Documents
。 您只需将集合定义放在文件的顶部或另一个不在server
或client
目录中的文件即可轻松实现。
打印前两个testing文档的示例可能如下所示:
Documents = new Meteor.Collection('testData'); if (Meteor.isClient) { Template.hello.greeting = function () { return "Welcome to apui."; }; Template.hello.events({ 'click input' : function () { var documents = Documents.find().fetch(); console.log(documents[0]); console.log(documents[1]); } }); }
请注意以下几点:
-
find
函数返回一个游标 。 编写模板代码时,这通常是你想要的。 但是,在这种情况下,我们需要直接访问文档来打印它们,所以我使用了光标上的fetch
。 请参阅文档了解更多详情。 - 当您第一次启动客户端时,服务器将读取定义的集合的内容,并将所有文档(如果已经
autopublish
发布)同步到客户端的本地minimongo数据库。 我将find
放置在click事件中以隐藏同步时间。 在你的代码中,find
会在客户端启动的瞬间执行,数据可能不会及时到达。
你的方法插入到数据库中的初始项目(你不需要use meteor
的方式),但是mongo将默认使用ObjectId
而不是string作为_id
。 有一些微妙的方法,这可能是一个meteor项目中的烦人,所以我的build议是让meteor插入你的数据,如果可能的话。 这里有一些代码可以确保testData
集合有一些文档:
if (Meteor.isServer) { Meteor.startup(function() { if (Documents.find().count() === 0) { console.log('inserting test data'); Documents.insert({name: "mongo"}); Documents.insert({x: 3}); } }); }
请注意,只有当collections中没有任何文档时才会执行此操作。 如果你想清除集合,你可以通过mongo控制台来完成。 或者,您可以删除整个数据库:
$ meteor reset