Fixing deprecated DB calls

master
Mark Moffat 2019-10-29 18:56:30 +10:30
parent 1d0b0ac5f0
commit 1584a2a173
13 changed files with 46 additions and 46 deletions

2
app.js
View File

@ -356,7 +356,7 @@ initDb(config.databaseConnectionString, async (err, db) => {
}); });
// Remove any invalid cart holds // Remove any invalid cart holds
await db.cart.remove({ await db.cart.deleteMany({
sessionId: { $nin: validSessionIds } sessionId: { $nin: validSessionIds }
}); });
}); });

View File

@ -500,7 +500,7 @@ const getData = (req, page, query) => {
// Run our queries // Run our queries
return Promise.all([ return Promise.all([
db.products.find(query).skip(skip).limit(parseInt(numberProducts)).toArray(), db.products.find(query).skip(skip).limit(parseInt(numberProducts)).toArray(),
db.products.count(query) db.products.countDocuments(query)
]) ])
.then((result) => { .then((result) => {
const returnData = { data: result[0], totalProducts: result[1] }; const returnData = { data: result[0], totalProducts: result[1] };

View File

@ -12,10 +12,10 @@ const config = getConfig();
initDb(config.databaseConnectionString, (err, db) => { initDb(config.databaseConnectionString, (err, db) => {
Promise.all([ Promise.all([
db.users.remove({}, {}), db.users.deleteMany({}, {}),
db.customers.remove({}, {}), db.customers.deleteMany({}, {}),
db.products.remove({}, {}), db.products.deleteMany({}, {}),
db.menu.remove({}, {}) db.menu.deleteMany({}, {})
]) ])
.then(() => { .then(() => {
Promise.all([ Promise.all([

View File

@ -29,7 +29,7 @@ router.get('/admin/logout', (req, res) => {
router.get('/admin/login', async (req, res) => { router.get('/admin/login', async (req, res) => {
const db = req.app.db; const db = req.app.db;
const userCount = await db.users.count({}); const userCount = await db.users.countDocuments({});
// we check for a user. If one exists, redirect to login form otherwise setup // we check for a user. If one exists, redirect to login form otherwise setup
if(userCount && userCount > 0){ if(userCount && userCount > 0){
// set needsSetup to false as a user exists // set needsSetup to false as a user exists
@ -80,7 +80,7 @@ router.post('/admin/login_action', async (req, res) => {
router.get('/admin/setup', async (req, res) => { router.get('/admin/setup', async (req, res) => {
const db = req.app.db; const db = req.app.db;
const userCount = await db.users.count({}); const userCount = await db.users.countDocuments({});
// dont allow the user to "re-setup" if a user exists. // dont allow the user to "re-setup" if a user exists.
// set needsSetup to false as a user exists // set needsSetup to false as a user exists
req.session.needsSetup = false; req.session.needsSetup = false;
@ -111,11 +111,11 @@ router.post('/admin/setup_action', async (req, res) => {
}; };
// check for users // check for users
const userCount = await db.users.count({}); const userCount = await db.users.countDocuments({});
if(userCount && userCount === 0){ if(userCount && userCount === 0){
// email is ok to be used. // email is ok to be used.
try{ try{
await db.users.insert(doc); await db.users.insertOne(doc);
req.session.message = 'User account inserted'; req.session.message = 'User account inserted';
req.session.messageType = 'success'; req.session.messageType = 'success';
res.redirect('/admin/login'); res.redirect('/admin/login');
@ -279,7 +279,7 @@ router.post('/admin/settings/pages/update', restrict, checkAccess, async (req, r
} }
try{ try{
await db.pages.update({ _id: common.getId(req.body.page_id) }, { $set: doc }, {}); await db.pages.updateOne({ _id: common.getId(req.body.page_id) }, { $set: doc }, {});
res.status(200).json({ message: 'Page updated successfully', page_id: req.body.page_id }); res.status(200).json({ message: 'Page updated successfully', page_id: req.body.page_id });
}catch(ex){ }catch(ex){
res.status(400).json({ message: 'Error updating page. Please try again.' }); res.status(400).json({ message: 'Error updating page. Please try again.' });
@ -287,7 +287,7 @@ router.post('/admin/settings/pages/update', restrict, checkAccess, async (req, r
}else{ }else{
// insert page // insert page
try{ try{
const newDoc = await db.pages.insert(doc); const newDoc = await db.pages.insertOne(doc);
res.status(200).json({ message: 'New page successfully created', page_id: newDoc._id }); res.status(200).json({ message: 'New page successfully created', page_id: newDoc._id });
return; return;
}catch(ex){ }catch(ex){
@ -300,7 +300,7 @@ router.post('/admin/settings/pages/update', restrict, checkAccess, async (req, r
router.get('/admin/settings/pages/delete/:page', restrict, checkAccess, async (req, res) => { router.get('/admin/settings/pages/delete/:page', restrict, checkAccess, async (req, res) => {
const db = req.app.db; const db = req.app.db;
try{ try{
await db.pages.remove({ _id: common.getId(req.params.page) }, {}); await db.pages.deleteOne({ _id: common.getId(req.params.page) }, {});
req.session.message = 'Page successfully deleted'; req.session.message = 'Page successfully deleted';
req.session.messageType = 'success'; req.session.messageType = 'success';
res.redirect('/admin/settings/pages'); res.redirect('/admin/settings/pages');
@ -365,7 +365,7 @@ router.post('/admin/api/validate_permalink', async (req, res) => {
query = { productPermalink: req.body.permalink, _id: { $ne: common.getId(req.body.docId) } }; query = { productPermalink: req.body.permalink, _id: { $ne: common.getId(req.body.docId) } };
} }
const products = await db.products.count(query); const products = await db.products.countDocuments(query);
if(products && products > 0){ if(products && products > 0){
res.status(400).json({ message: 'Permalink already exists' }); res.status(400).json({ message: 'Permalink already exists' });
return; return;
@ -429,7 +429,7 @@ router.post('/admin/file/upload', restrict, checkAccess, upload.single('upload_f
// if there isn't a product featured image, set this one // if there isn't a product featured image, set this one
if(!product.productImage){ if(!product.productImage){
await db.products.update({ _id: common.getId(req.body.productId) }, { $set: { productImage: imagePath } }, { multi: false }); await db.products.updateOne({ _id: common.getId(req.body.productId) }, { $set: { productImage: imagePath } }, { multi: false });
req.session.message = 'File uploaded successfully'; req.session.message = 'File uploaded successfully';
req.session.messageType = 'success'; req.session.messageType = 'success';
res.redirect('/admin/product/edit/' + req.body.productId); res.redirect('/admin/product/edit/' + req.body.productId);

View File

@ -216,7 +216,7 @@ router.post('/customer/forgotten_action', (req, res) => {
// if we have a customer, set a token, expiry and email it // if we have a customer, set a token, expiry and email it
if(customer){ if(customer){
const tokenExpiry = Date.now() + 3600000; const tokenExpiry = Date.now() + 3600000;
db.customers.update({ email: req.body.email }, { $set: { resetToken: passwordToken, resetTokenExpiry: tokenExpiry } }, { multi: false }, (err, numReplaced) => { db.customers.updateOne({ email: req.body.email }, { $set: { resetToken: passwordToken, resetTokenExpiry: tokenExpiry } }, { multi: false }, (err, numReplaced) => {
// send forgotten password email // send forgotten password email
const mailOpts = { const mailOpts = {
to: req.body.email, to: req.body.email,
@ -282,7 +282,7 @@ router.post('/customer/reset/:token', (req, res) => {
// update the password and remove the token // update the password and remove the token
const newPassword = bcrypt.hashSync(req.body.password, 10); const newPassword = bcrypt.hashSync(req.body.password, 10);
db.customers.update({ email: customer.email }, { $set: { password: newPassword, resetToken: undefined, resetTokenExpiry: undefined } }, { multi: false }, (err, numReplaced) => { db.customers.updateOne({ email: customer.email }, { $set: { password: newPassword, resetToken: undefined, resetTokenExpiry: undefined } }, { multi: false }, (err, numReplaced) => {
const mailOpts = { const mailOpts = {
to: customer.email, to: customer.email,
subject: 'Password successfully reset', subject: 'Password successfully reset',

View File

@ -39,7 +39,7 @@ router.get('/payment/:orderId', async (req, res, next) => {
} }
// Update product stock // Update product stock
await db.products.update({ await db.products.updateOne({
_id: getId(product.productId) _id: getId(product.productId)
}, { }, {
$set: { $set: {
@ -221,7 +221,7 @@ router.post('/product/updatecart', (req, res, next) => {
updateTotalCartAmount(req, res); updateTotalCartAmount(req, res);
// Update cart to the DB // Update cart to the DB
await db.cart.update({ sessionId: req.session.id }, { await db.cart.updateOne({ sessionId: req.session.id }, {
$set: { cart: req.session.cart } $set: { cart: req.session.cart }
}); });
@ -254,7 +254,7 @@ router.post('/product/removefromcart', (req, res, next) => {
callback(); callback();
}, async () => { }, async () => {
// Update cart in DB // Update cart in DB
await db.cart.update({ sessionId: req.session.id }, { await db.cart.updateOne({ sessionId: req.session.id }, {
$set: { cart: req.session.cart } $set: { cart: req.session.cart }
}); });
// update total cart amount // update total cart amount
@ -276,7 +276,7 @@ router.post('/product/emptycart', async (req, res, next) => {
delete req.session.orderId; delete req.session.orderId;
// Remove cart from DB // Remove cart from DB
await db.cart.removeOne({ sessionId: req.session.id }); await db.cart.deleteOne({ sessionId: req.session.id });
// update total cart amount // update total cart amount
updateTotalCartAmount(req, res); updateTotalCartAmount(req, res);
@ -387,7 +387,7 @@ router.post('/product/addtocart', async (req, res, next) => {
} }
// Update cart to the DB // Update cart to the DB
await db.cart.update({ sessionId: req.session.id }, { await db.cart.updateOne({ sessionId: req.session.id }, {
$set: { cart: req.session.cart } $set: { cart: req.session.cart }
}, { upsert: true }); }, { upsert: true });

View File

@ -136,7 +136,7 @@ router.get('/admin/order/delete/:id', restrict, (req, res) => {
const db = req.app.db; const db = req.app.db;
// remove the order // remove the order
db.orders.remove({ _id: common.getId(req.params.id) }, {}, (err, numRemoved) => { db.orders.deleteOne({ _id: common.getId(req.params.id) }, {}, (err, numRemoved) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -154,7 +154,7 @@ router.get('/admin/order/delete/:id', restrict, (req, res) => {
// update order status // update order status
router.post('/admin/order/statusupdate', restrict, checkAccess, (req, res) => { router.post('/admin/order/statusupdate', restrict, checkAccess, (req, res) => {
const db = req.app.db; const db = req.app.db;
db.orders.update({ _id: common.getId(req.body.order_id) }, { $set: { orderStatus: req.body.status } }, { multi: false }, (err, numReplaced) => { db.orders.updateOne({ _id: common.getId(req.body.order_id) }, { $set: { orderStatus: req.body.status } }, { multi: false }, (err, numReplaced) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
return res.status(400).json({ message: 'Failed to update the order status' }); return res.status(400).json({ message: 'Failed to update the order status' });

View File

@ -76,7 +76,7 @@ router.post('/checkout_action', (req, res, next) => {
}; };
// insert order into DB // insert order into DB
db.orders.insert(orderDoc, (err, newDoc) => { db.orders.insertOne(orderDoc, (err, newDoc) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }

View File

@ -67,7 +67,7 @@ router.get('/checkout_return', (req, res, next) => {
} }
// update the order status // update the order status
db.orders.update({ _id: common.getId(paymentOrderId) }, { $set: { orderStatus: paymentStatus } }, { multi: false }, (err, numReplaced) => { db.orders.updateOne({ _id: common.getId(paymentOrderId) }, { $set: { orderStatus: paymentStatus } }, { multi: false }, (err, numReplaced) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -186,7 +186,7 @@ router.post('/checkout_action', (req, res, next) => {
res.redirect(redirectUrl); res.redirect(redirectUrl);
}else{ }else{
// no order ID so we create a new one // no order ID so we create a new one
db.orders.insert(orderDoc, (err, newDoc) => { db.orders.insertOne(orderDoc, (err, newDoc) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }

View File

@ -56,7 +56,7 @@ router.post('/checkout_action', (req, res, next) => {
}; };
// insert order into DB // insert order into DB
db.orders.insert(orderDoc, (err, newDoc) => { db.orders.insertOne(orderDoc, (err, newDoc) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }

View File

@ -124,7 +124,7 @@ router.post('/admin/product/insert', restrict, checkAccess, async (req, res) =>
} }
// Check permalink doesn't already exist // Check permalink doesn't already exist
const product = await db.products.count({ productPermalink: req.body.productPermalink }); const product = await db.products.countDocuments({ productPermalink: req.body.productPermalink });
if(product > 0 && req.body.productPermalink !== ''){ if(product > 0 && req.body.productPermalink !== ''){
// permalink exits // permalink exits
req.session.message = 'Permalink already exists. Pick a new one.'; req.session.message = 'Permalink already exists. Pick a new one.';
@ -239,7 +239,7 @@ router.post('/admin/product/removeoption', restrict, checkAccess, async (req, re
delete opts[req.body.optName]; delete opts[req.body.optName];
try{ try{
const updateOption = await db.products.update({ _id: common.getId(req.body.productId) }, { $set: { productOptions: opts } }); const updateOption = await db.products.updateOne({ _id: common.getId(req.body.productId) }, { $set: { productOptions: opts } });
if(updateOption.result.nModified === 1){ if(updateOption.result.nModified === 1){
res.status(200).json({ message: 'Option successfully removed' }); res.status(200).json({ message: 'Option successfully removed' });
return; return;
@ -273,7 +273,7 @@ router.post('/admin/product/update', restrict, checkAccess, async (req, res) =>
res.redirect('/admin/product/edit/' + req.body.productId); res.redirect('/admin/product/edit/' + req.body.productId);
return; return;
} }
const count = await db.products.count({ productPermalink: req.body.productPermalink, _id: { $ne: common.getId(product._id) } }); const count = await db.products.countDocuments({ productPermalink: req.body.productPermalink, _id: { $ne: common.getId(product._id) } });
if(count > 0 && req.body.productPermalink !== ''){ if(count > 0 && req.body.productPermalink !== ''){
// If API request, return json // If API request, return json
if(req.apiAuthenticated){ if(req.apiAuthenticated){
@ -365,7 +365,7 @@ router.post('/admin/product/update', restrict, checkAccess, async (req, res) =>
} }
try{ try{
await db.products.update({ _id: common.getId(req.body.productId) }, { $set: productDoc }, {}); await db.products.updateOne({ _id: common.getId(req.body.productId) }, { $set: productDoc }, {});
// Update the index // Update the index
indexProducts(req.app) indexProducts(req.app)
.then(() => { .then(() => {
@ -398,7 +398,7 @@ router.get('/admin/product/delete/:id', restrict, checkAccess, async (req, res)
const db = req.app.db; const db = req.app.db;
// remove the product // remove the product
await db.products.remove({ _id: common.getId(req.params.id) }, {}); await db.products.deleteOne({ _id: common.getId(req.params.id) }, {});
// delete any images and folder // delete any images and folder
rimraf('public/uploads/' + req.params.id, (err) => { rimraf('public/uploads/' + req.params.id, (err) => {
@ -422,7 +422,7 @@ router.post('/admin/product/published_state', restrict, checkAccess, async (req,
const db = req.app.db; const db = req.app.db;
try{ try{
await db.products.update({ _id: common.getId(req.body.id) }, { $set: { productPublished: common.convertBool(req.body.state) } }, { multi: false }); await db.products.updateOne({ _id: common.getId(req.body.id) }, { $set: { productPublished: common.convertBool(req.body.state) } }, { multi: false });
res.status(200).json('Published state updated'); res.status(200).json('Published state updated');
}catch(ex){ }catch(ex){
console.error(colors.red('Failed to update the published state: ' + ex)); console.error(colors.red('Failed to update the published state: ' + ex));
@ -436,7 +436,7 @@ router.post('/admin/product/setasmainimage', restrict, checkAccess, async (req,
try{ try{
// update the productImage to the db // update the productImage to the db
await db.products.update({ _id: common.getId(req.body.product_id) }, { $set: { productImage: req.body.productImage } }, { multi: false }); await db.products.updateOne({ _id: common.getId(req.body.product_id) }, { $set: { productImage: req.body.productImage } }, { multi: false });
res.status(200).json({ message: 'Main image successfully set' }); res.status(200).json({ message: 'Main image successfully set' });
}catch(ex){ }catch(ex){
res.status(400).json({ message: 'Unable to set as main image. Please try again.' }); res.status(400).json({ message: 'Unable to set as main image. Please try again.' });
@ -455,7 +455,7 @@ router.post('/admin/product/deleteimage', restrict, checkAccess, async (req, res
} }
if(req.body.productImage === product.productImage){ if(req.body.productImage === product.productImage){
// set the productImage to null // set the productImage to null
await db.products.update({ _id: common.getId(req.body.product_id) }, { $set: { productImage: null } }, { multi: false }); await db.products.updateOne({ _id: common.getId(req.body.product_id) }, { $set: { productImage: null } }, { multi: false });
// remove the image from disk // remove the image from disk
fs.unlink(path.join('public', req.body.productImage), (err) => { fs.unlink(path.join('public', req.body.productImage), (err) => {

View File

@ -71,7 +71,7 @@ router.get('/admin/user/new', restrict, (req, res) => {
router.get('/admin/user/delete/:id', restrict, (req, res) => { router.get('/admin/user/delete/:id', restrict, (req, res) => {
const db = req.app.db; const db = req.app.db;
if(req.session.isAdmin === true){ if(req.session.isAdmin === true){
db.users.remove({ _id: common.getId(req.params.id) }, {}, (err, numRemoved) => { db.users.deleteOne({ _id: common.getId(req.params.id) }, {}, (err, numRemoved) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -120,7 +120,7 @@ router.post('/admin/user/update', restrict, (req, res) => {
updateDoc.userPassword = bcrypt.hashSync(req.body.userPassword); updateDoc.userPassword = bcrypt.hashSync(req.body.userPassword);
} }
db.users.update({ _id: common.getId(req.body.userId) }, db.users.updateOne({ _id: common.getId(req.body.userId) },
{ {
$set: updateDoc $set: updateDoc
}, { multi: false }, (err, numReplaced) => { }, { multi: false }, (err, numReplaced) => {
@ -147,7 +147,7 @@ router.post('/admin/user/insert', restrict, (req, res) => {
const urlParts = new URL(req.header('Referer')); const urlParts = new URL(req.header('Referer'));
// Check number of users // Check number of users
db.users.count({}, (err, userCount) => { db.users.countDocuments({}, (err, userCount) => {
let isAdmin = false; let isAdmin = false;
// if no users, setup user as admin // if no users, setup user as admin
@ -173,7 +173,7 @@ router.post('/admin/user/insert', restrict, (req, res) => {
return; return;
} }
// email is ok to be used. // email is ok to be used.
db.users.insert(doc, (err, doc) => { db.users.insertOne(doc, (err, doc) => {
// show the view // show the view
if(err){ if(err){
if(doc){ if(doc){

View File

@ -19,11 +19,11 @@ let request = null;
function setup(db){ function setup(db){
return Promise.all([ return Promise.all([
db.cart.remove({}, {}), db.cart.deleteMany({}, {}),
db.users.remove({}, {}), db.users.deleteMany({}, {}),
db.customers.remove({}, {}), db.customers.deleteMany({}, {}),
db.products.remove({}, {}), db.products.deleteMany({}, {}),
db.orders.remove({}, {}) db.orders.deleteMany({}, {})
]) ])
.then(() => { .then(() => {
return Promise.all([ return Promise.all([
@ -65,7 +65,7 @@ test.before(async () => {
productComment: null productComment: null
}); });
order.orderDate = new Date(); order.orderDate = new Date();
await db.orders.insert(order); await db.orders.insertOne(order);
}); });
// Index everything // Index everything