Use the native mogodb driver to limit the number of array returns in node.js. The same syntax works on the command line, but not in node.

Native mogodb driver is used in node.js to limit the number of array returns. The same syntax works on the command line, but does not work in node

I want to do a paging query DEMO, wants to use db.collection.find ({"_ id": ObjectId (_ id)}, {"comments": {"$slice": 1}}), but the result of the query is still to query all the data of the array comments

the code is as follows
     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; iPP) {
              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]);
          }
        });

did not report an error, but returned all the data and expected to see the data returned according to the restrictions.

Apr.01,2021

you can coat {"comments": {"$slice": 1} with a layer of projection .
eventually becomes findOne ({"_ id": ObjectId (user_id)}, {projection: {"comments": {"$slice": 1}


since you use the findOne method to check, in theory, only one document will be returned. You console.log (item) in the callback function to see if it is a document.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b326e7-2b666.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b326e7-2b666.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?