[英]Meteor Mongo Not Getting Collection Data
我正在嘗試從集合中獲取文檔,但是它似乎沒有用。
當我使用find()。fetch()時,它僅返回一個空數組。 我的代碼如下。
var users = new Mongo.Collection("users");
console.log(users.find());
var userRecord = users.find().fetch();
var returnUserRecord = {};
if (userRecord.length >0){
returnUserRecord = {username:userRecord.username, loginHash:userRecord.loginHash};
console.log("if statement is not complete and the value of the return variable is");
console.log(returnUserRecord);
}
return returnUserRecord
我已經直接檢查了數據庫,發現使用命令命令集合中確實存在一個文檔:
meteor mongo
如果有任何區別,則所有這些代碼都在服務器js文件中,並通過以下方式從客戶端調用:Meteor.Methods()/ Meteor.call()
我選擇了正確的數據庫並運行以下命令后,從客戶端使用新數據創建了另一個集合:
meteor:PRIMARY> db.newCollection1.find()
我得到:
{ "_id" : ObjectId("55d1fa4686ee75349cd73ffb"), "test1" : "asdasd", "test2" : "dsadsa", "test3" : "qweqwe" }
因此,這確認它在數據庫中可用,但是在客戶端控制台中運行以下命令仍不會返回結果。 (安裝了autopublish。我嘗試刪除autopublish,並進行了適當的更改以訂閱該表,但這也不起作用)。
var coll = new Meteor.Collection('newCollection1');
coll.find().fetch()
這返回一個空數組。 我也使用以下方法在server.js代碼上嘗試了相同的操作:
meteor debug
但我仍然得到一個空數組。 有人知道我在這里可能做錯了嗎?
解決方案是在Meteor對象上下文中創建collection變量。 這樣就可以從流星上下文中訪問它。
即
Meteor.coll = new Meteor.Collection('newCollection1');
Meteor.coll.find().fetch();
我希望這可以幫助別人。 根據您的代碼,您可能希望使用其他上下文。
您是否在某個地方訂閱了users
收藏集?
if (Meteor.isServer) {
Meteor.publish("users", function(){
return Users.find({})
});
}
if (Meteor.isClient) {
Meteor.subscribe("users");
}
首先一些建議:不能兩次定義一個集合。 如果第二次調用new Mongo.Collection("users")
,則會收到錯誤消息。 因此,它應該是全局變量,而不是方法內部。
我在您的代碼中看到的是,您試圖像使用對象一樣使用數組。 userRecord.username
因為userRecord
具有返回數組的fetch()
的值。
您可以將代碼更改為userRecord[0].username
,也可以使用forEach
遍歷結果,如下所示:
var users = new Mongo.Collection("users");
console.log(users.find());
users.find().forEach(function(singleUser){
console.log(EJSON.stringyfy(singleUser));
}
為了返回第一個用戶,最好使用findOne
返回結果中的第一個對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.