1.首先,先分享用來作分頁查詢的簡單函數,先上代碼,git
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爲一頁顯示多少條。github
2.說說Node.js操做mongodb時怎麼對數據庫裏面的數組進行增刪該查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)