鍍金池/ 問答/C++  數(shù)據(jù)庫  HTML/ 在node.js中使用原生mogodb驅(qū)動(dòng)限制數(shù)組返回?cái)?shù)量,同樣語法在命令行中起

在node.js中使用原生mogodb驅(qū)動(dòng)限制數(shù)組返回?cái)?shù)量,同樣語法在命令行中起作用,在node中不生效

在node.js中使用原生mogodb驅(qū)動(dòng)限制數(shù)組返回?cái)?shù)量,同樣語法在命令行中起作用,在node中不生效

我想做一個(gè)分頁查詢的DEMO,想使用db.collection.find({"_id":ObjectId(_id)},{"comments":{"$slice":1}})可是查詢出來的結(jié)果仍是把數(shù)組comments的數(shù)據(jù)全部查詢出來了

代碼如下
     dbase
        .collection("userInfo")
        .findOne({ "_id": ObjectId(user_id)},{"comments":{"$slice":1}}, function(err, item) {
          if (err) {
            reject("faith");
            throw new Error("查詢出錯(cuò)");
          } 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]);
          }
        });

沒有報(bào)錯(cuò),返回的是全部數(shù)據(jù),期望看到根據(jù)限制條件返回的數(shù)據(jù)。

回答
編輯回答
咕嚕嚕

你在{"comments":{"$slice":1}這個(gè)外面套一層 projection 就可以了。
最終變成findOne({ "_id": ObjectId(user_id)},{projection: {"comments":{"$slice":1}}}

2017年6月23日 06:05
編輯回答
青瓷

你既然用findOne方法去查,理論上只會(huì)返回一條文檔,你在回調(diào)函數(shù)中console.log(item),看看是不是一條文檔。

2018年9月5日 08:01