【问题标题】:How to specify read preference in Meteor's mongo queries如何在 Meteor 的 mongo 查询中指定读取偏好
【发布时间】:2018-07-14 04:50:36
【问题描述】:

在 Meteor Mongo 中,如何在 Meteor Mongo Query 中指定 readPref 到 primary|secondary。

【问题讨论】:

  • 我的回答对您有帮助还是您的问题仍然存在?

标签: mongodb meteor


【解决方案1】:

我希望以下内容可以更好地理解 Meteor 和 Mongo 之间的关系。


流星系列更舒适

Meteor 为您提供完整的 mongo 功能。然而,为了舒适,它提供了一个 mongo 集合的wrapped API,它与 Meteor 环境集成得最好。因此,如果您通过

导入 Mongo
import { Mongo } from 'meteor/mongo' 

您主要导入包装好的 mongo 集合,其中操作在 Meteor 光纤中执行。这些包装集合的查询返回的游标也不是“自然”游标,而是要进行 Meteor 优化的 wrapped cursors

如果您尝试访问这些实例上未实现的本机功能,您将收到错误消息。在你的情况下:

import { Meteor } from 'meteor/meteor';
import { Random } from 'meteor/random';

const ExampleCollection = new Mongo.Collection('examples')

Meteor.startup(() => {
  // code to run on server at startup
  ExampleCollection.insert({ value: Random.id() })
  const docsCursor = ExampleCollection.find();
  docsCursor.readPref('primary')
}); 

导致

TypeError: docsCursor.readPref is not a function


访问节点mongo驱动集合

好消息是,you can access the layer underneath 通过Collection.rawCollection() 您可以完全访问节点 Mongo 驱动程序。这是因为 Meteor 的 Mongo.CollectionCursor 最终都在使用这个原生驱动程序。

现在你会发现另外两个问题:

  1. readPref 在 node-mongo 游标 cursor.setReadPreference (3.1 API) 中命名。

  2. Cursor.fetch 不存在,但被命名为 cursor.toArray,它(与许多本机操作一样)返回一个 Promise


所以最后回答你的问题

您可以执行以下操作:

import { Meteor } from 'meteor/meteor';
import { Random } from 'meteor/random';

const ExampleCollection = new Mongo.Collection('examples')

Meteor.startup(() => {
  // code to run on server at startup

  ExampleCollection.insert({ value: Random.id() })
  const docsCursor = ExampleCollection.rawCollection().find();
  docsCursor.setReadPreference('primary')
  docsCursor.toArray().then((docs) => {
    console.log(docs)
  }).catch((err)=> console.error(err))
});


总结

  • 通过使用collection.rawCollection(),您可以访问node mongo driver API 的全部范围

  • 您可以自行将操作、游标和结果 (Promises) 集成到您的环境中。好帮手是Meteor.bindEnvironmentMeteor.wrapAsync

  • 注意 node-mongo 驱动程序的 API 更改。一方面是驱动支持的mongo版本,另一方面是Meteor支持的驱动版本。

  • 请注意,使用本机 API 更容易“搞砸”事情,但它也为您提供了许多新选项。小心使用。

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 2019-04-23
    相关资源
    最近更新 更多