在node.js中使用原生mogodb驱动限制数组返回数量,同样语法在命令行中起作用,在node中不生效

在node.js中使用原生mogodb驱动限制数组返回数量,同样语法在命令行中起作用,在node中不生效

我想做一个分页查询的DEMO,想使用db.collection.find({"_id":ObjectId(_id)},{"comments":{"$slice":1}})可是查询出来的结果仍是把数组comments的数据全部查询出来了

代码如下
     dbase
        .collection("userInfo")
        .findOne({ "_id": ObjectId(user_id)},{"comments":{"$slice":1}}, function(err, item) {
          if (err) {
            reject("faith");
            throw new Error("查询出错");
          } else {
            let articalData = [];
            for (let i = 0; i < item.comments.length; i++) {
              articalData.push({
                _id: item.comments[i].id,
                desc: item.comments[i].desc,
                content: item.comments[i].content,
                authorName: item.comments[i].name,
                title: item.comments[i].title,
                time: item.comments[i].time
              });
            }
            let data = {
              code: 0,
              name: item.name,
              articalData: articalData,
              sumPage:item.comments.length%2?Number.parseInt(item.comments.length/2)+1:item.comments.length/2
            };
            resolve([dbase, data]);
          }
        });

没有报错,返回的是全部数据,期望看到根据限制条件返回的数据。

阅读 2k
2 个回答

你在{"comments":{"$slice":1}这个外面套一层 projection 就可以了。
最终变成findOne({ "_id": ObjectId(user_id)},{projection: {"comments":{"$slice":1}}}

你既然用findOne方法去查,理论上只会返回一条文档,你在回调函数中console.log(item),看看是不是一条文档。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题