在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]);
}
});
没有报错,返回的是全部数据,期望看到根据限制条件返回的数据。
你在
{"comments":{"$slice":1}
这个外面套一层projection
就可以了。最终变成
findOne({ "_id": ObjectId(user_id)},{projection: {"comments":{"$slice":1}}}