Mongoose:禁用返回文档的空查询

时间:2016-02-04 20:05:03

标签: node.js mongoose

当使用Mongoose(在我的情况下使用bluebird,但使用回调来说明)时,以下代码都返回集合中的文档:

model.findOne({}, function(err, document) {
    //returns a document
})
model.findOne(null, function(err, document) {
    //returns a document
})
model.findOne([], function(err, document) {
    //returns a document
})

我想知道是否以及如何禁用这种行为,因为它对我的代码负有责任,我从用户输入系统的数据中推断查询。特别是返回有效文档的null查询让我很担心。

到目前为止,我检查输入是非空的,非数组,非空对象,但它在规模上变得有点麻烦。

排除此行为的最佳方式是什么?

1 个答案:

答案 0 :(得分:0)

不确定这是不是最好的方法,但是现在我已经决定在模型本身上使用预挂钩来检查'这个&#39的_conditions属性。 ;对象(我从打印中推断似乎持有查询对象)不为空。

在下一个功能中插入自定义对象会导致Promise拒绝最初调用查询。

(_是下划线包)

//model.js
//model is a mongoose.Schema type in the following code

model.pre('findOne', function(next) {
  var self = this

  if (_.isEmpty(self._conditions)) {
    next(mainErrors.malformedRequest)
  } else {
    next()
  }
})
相关问题