Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Mongoose:禁用返回文档的空查询_Node.js_Mongoose - Fatal编程技术网

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

Node.js Mongoose:禁用返回文档的空查询,node.js,mongoose,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) {

使用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
})
我想知道是否以及如何禁用这种行为,因为在我的代码中,从用户输入到系统的数据推断查询,这将成为一种负担。尤其是返回有效文档的空查询让我担心

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


排除这种行为的最佳方法是什么?

不确定这是否是最好的方法,但现在我决定在模型本身上使用一个预钩子,它检查“this”对象的_conditions属性(我从打印中推断出该属性似乎保持查询对象)是否为空

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

(u是下划线包)


您首先不应该信任用户。因为findOne将一个对象作为第一个参数,所以至少应该检查它是否是一个对象。如果传入的数据不正确,则无法期望得到正确的结果。
//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()
  }
})