1.首先,先分享用来做分页查询的简单函数,先上代码,

function findByPagination(collections, selector, page, count, fn) {
    let skipnumber = (page - 1) * count;
    let totalCount;
    MongoClient.connect(Urls, function (err, db) {
        let collection = db.collection(collections);
        assert.equal(null, err);
        console.log("Connected correctly to server");

        collection.find(selector).count((err, res) => {
            assert.equal(err, null);
            totalCount = res;
        });
        collection.find(selector).skip(skipnumber).limit(count).toArray(function (err, result) {
            try {
                assert.equal(err, null);
                fn({
                    success: true,
                    data: result,
                    totalCount: totalCount
                });
            } catch (e) {
                console.log(e);
                fn({
                    success: false,
                    data: [],
                    totalCount: totalCount
                });
            }

        });
        db.close();
    });

page是当前页数,count为一页显示多少条。

2.说说Node.js操作mongodb时怎么对数据库里面的数组进行增删该查

if (req.session.userId) {
        let bookId = req.body.bookId;
        let quantity = req.body.quantity;
        let totalNum = req.body.totalNum;
        console.log('quantity: ', quantity);
        req.session.userId = req.session.userId;
        handleDb("userCollection", [{ _id: new ObjectID(req.session.userId), cart: { $elemMatch: { bookID: new ObjectID(bookId) } } }, { $set: { 'cart.$.quantity': quantity, totalnum: totalNum } }], update, data => {
            res.end(`{"totalNum":${totalNum}}`);
        })
    }

这里的if判断req.session.userId是否存在,不太理解为什么一定要这么写,不这样写刷新一次session就会变成undifine,大概是每次访问时session都是不一样的req吧,猜的
这里查询的意思是对cart数组里指定ID的书籍的数量进行设置,如果把$set改成$inc就是指定Id的书籍的数量进行增加

handleDb("userCollection", [{ _id: new ObjectID(req.session.userId) }, { $pull: { cart: { bookID: new ObjectID(bookId) } } }], update, data => {
            handleDb("userCollection", { _id: new ObjectID(req.session.userId) }, find, userdata => {
                let user = userdata.data[0];
                let totalnum = user.totalnum;
                res.end(`{"totalNum":${totalnum}}`);
            })
        })

删除cart数组中包含指定bookID的项目

最后贴上Mean stack写的简单的书店前后端交互Demo

[图书在线商城](https://github.com/ZoeLeee/bookstore)

ZoeLee
104 声望4 粉丝

不忘初心