Mongodb中limit()和$ limit之间的区别

时间:2018-11-29 04:27:20

标签: mongodb mongodb-stitch

在我的前端内部,对用户进行身份验证之后,我可以使用以下代码: ..

...
.then(authedUser =>
        db
          .collection('comments')
          .find({}, { limit: 1 })
          .asArray()
      )
      .then(doc => console.log('doc:', doc)); // 1 doc returned as array, yes!

但是,以下代码不起作用:

...
.then(authedUser =>
        db
          .collection('comments')
          .find({})
          .limit(1)
          .asArray()
      )
      .then(doc => console.log('doc:', doc)); // error inside Promise, limit is not a function...

我可以知道为什么吗?我知道limit()是一个游标方法,而$ limit是一个聚合阶段,所以现在我有点困惑。

2 个答案:

答案 0 :(得分:0)

这在文档中有些混乱,因为第二个可以在Stitch函数中使用,但在使用SDK时不起作用。第一种是从SDK执行此操作的正确方法。在SDK中,读取操作没有修饰符,这意味着您无法在find()上调用f.write(bytes(html, 'UTF-8'))

这里是您所做的enter image description here。希望这可以帮助!

答案 1 :(得分:-1)

limit()
  

当关键字以括号结尾时,表示方法被调用

$limit 
  

当关键字以美元开头时,表示运算符$limit operator

     

$ limit仅适用于聚合

现在根据您的问题

.then(authedUser =>
        db
          .collection('comments')
          .find({}, { limit: 1 })
          .asArray()
      )
      .then(doc => console.log('doc:', doc));

在这里您将限制作为option参数中的3rd传递,其中1表示为true

以及第二个代码

.then(authedUser =>
        db
          .collection('comments')
          .find({})
          .limit(1)
          .exec(function(err, result) {
              // Do here as a array
              return new Promise((resolve, reject) => {})
           });              
      )
      .then(doc => console.log('doc:', doc));

您将limit方法称为cascading style(Chaining Methods)

并且都在限制结果