检查对象是否是mongo游标

check if object is a mongo cursor

本文关键字:游标 mongo 是否是 对象 检查      更新时间:2023-09-26

我有一个方法,我想在其中接收列表或mongo光标并对此做出反应,例如:

createFromTemplate: function(template) {
  var iter;
  if(template instanceof Mongo.Cursor) {
    iter = template.fetch();
  } else if(template instanceof Array) {
    iter = template;
  } else {
    throw new Meteor.Error(500, 'Template must be a Cursor or Array');
  }
}

然而,当我不期望它时,它似乎返回错误

> var p = PageTemplates.find();  // as a mongo cursor
> var pArray = p.fetch();        // as an array
> Object.prototype.toString.call(p);
[object Object]
> typeof p
Object
> p instanceof Mongo.Cursor
false

如何判断一个对象是否是Mongo光标?

您应该能够使用instanceof Mongo.Collection.Cursor(而不是Mongo.Cursor)。从我的控制台:

> a = Meteor.users.find()
<- LocalCollection.Cursor {collection: LocalCollection, sorter: null, _selectorId: undefined, matcher: Minimongo.Matcher, skip: undefined…}
> a instanceof Mongo.Collection.Cursor
<- true