簡體   English   中英

如何在Meteor 1.3中僅使用集合名稱獲取集合?

[英]How to get Collection using only collection name in Meteor 1.3?

在我的項目中,我使用的包需要集合名稱才能在集合內進行一些搜索。 我剛剛遷移到Meteor 1.3,現在此程序包不起作用。

在代碼包中,使用類似以下內容的代碼:

const search = (collection_name) => {
   let collection = this[collection_name]
   ...
}

現在,收藏已不在全球范圍內。 我可以在lib/collections.js在其中添加global[collection_name] = Collection lib/collections.js ,但我想修復軟件包以使其更加靈活並與Meteor 1.3兼容。

如果您僅知道集合名稱,是否有可能獲得Mongo集合?

我建議您創建一個全局對象來保存您的集合,而不是使用似乎是私有的api(可能會在不通知的情況下更改,如Archimedes所建議), 流星文檔特別指出:

Generally, you'll assign Mongo.Collection objects in your app to global variables. You can only create one Mongo.Collection object for each underlying Mongo collection.

因此,如果您具有全局的Collections ,則可以通過Collections[name]輕松訪問有問題的Collections[name] 當然,您確實想限制全局變量,因此,如果您當前對應用程序有全局變量,只需為其提供一個屬性來保存您的集合。 以下是一種通用模式,無論您的集合位於單個文件中還是位於單獨文件中,您都可以根據需要進行調整。

app = app || {};
app.collections = {
    // collections here
}

感謝@sashko的建議,我查看了https://github.com/dburles/mongo-collection-instances ,然后查看了lai:collection-extensions ,這是我解決的方法:

import { CollectionExtensions } from 'meteor/lai:collection-extensions'

let registered_collections = {}
CollectionExtensions.addExtension(function (name, options) {
  registered_collections[name] = {
    name: name,
    instance: this,
    options: options
  };
});

export function getCollectionByName(collecion_name) {
    return registered_collections[collecion_name].instance
}

使用以下技術

Meteor.default_connection._mongo_livedata_collections.users.find({}).fetch()

只需用您擁有的任何集合替換用戶。

https://forums.meteor.com/t/es6-global-collection-variables/22392/2?u=trajano

嘗試以下魔術(在客戶端代碼中):

Meteor.connection._stores['tasks']._getCollection()

欲了解更多信息,請結帳:

流星/流星#5845 (首次嘗試於2015年12月進行)

流星/流星#6160 (2016年2月修復)

或者,如果您更喜歡公共API,並且不介意其他依賴項,請使用另一個答案中提到的mongo-collection-instances

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM