如何在流星的mongo查询中指定读取首选项 [英] How to specify read preference in Meteor's mongo queries

查看:82
本文介绍了如何在流星的mongo查询中指定读取首选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Meteor Mongo中,如何在Meteor Mongo查询中将readPref指定为primary | secondary.

In Meteor Mongo, how to specify the readPref to primary|secondary in Meteor Mongo Query.

推荐答案

我希望以下内容可以更好地理解流星与Mongo之间的关系.


I hope the following provides a better understanding of the relationship between Meteor and Mongo.


Meteor为您提供完整的mongo功能.但是,为了方便起见,它提供了一个与mongo集合集成的包装的API 最适合流星环境.因此,如果您通过

Meteor provides you with the full mongo functionality. However for comfort it provides a wrapped API of a mongo collection that integrates best with the Meteor environment. So if you import Mongo via

import { Mongo } from 'meteor/mongo' 

您主要是导入包装的mongo集合,在其中用Meteor光纤执行操作.这些包装的集合的查询返回的游标也不是自然"游标,而是包装的光标进行流星优化.

you primarily import the wrapped mongo collection where operations are executed in a Meteor fiber. The cursor that is returned by queries of these wrapped collections are also not the "natural" cursors but also wrapped cursors to be Meteor optimized.

如果您尝试在未实现的这些实例上访问本机功能,则会收到错误消息.就您而言:

If you try to access a native feature on these instances that is not implemented you will receive an error. In your case:

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


好消息是,您可以访问其下的层Collection.rawCollection()通过a>可以完全访问节点Mongo驱动程序.这是因为Meteor的Mongo.CollectionCursor最终都在使用此本机驱动程序.

The good news is, you can access the layer underneath via Collection.rawCollection() where you have full access to the node Mongo driver. This is because under the hood Meteor's Mongo.Collection and it's Cursor are making use of this native driver in the end.

现在您将发现另外两个问题:

Now you will find two other issues:

  1. readPref在节点mongo游标中命名 cursor.setReadPreference (3.1 API).

  1. readPref is named in a node-mongo cursor cursor.setReadPreference (3.1 API).

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

Cursor.fetch does not exist but is named cursor.toArray which (as many native operations do) returns a 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))
});


查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆