Mongoose - bigktmbig/MyExperienceAlgorithm GitHub Wiki
-
call prototype function Post.find({}).sort('test').exec(function(err, docs) { ... }); Post.find({}).sort('date', -1).exec(function(err, docs) { ... }); Post.find({}).sort({test: 1}).exec(function(err, docs) { ... }); Post.find({}, null, {sort: {date: 1}}, function(err, docs) { ... });
-
save not working, let follow me: item.markModified('shop_list'); item.save(function(err, data){});
-
push a field array in item var objFriends = { fname:"fname",lname:"lname",surname:"surname" }; Friend.findOneAndUpdate( { _id: req.body.id }, { $push: { friends: objFriends } }, function (error, success) { if (error) { console.log(error); } else { console.log(success); } }); )
-
update a field in array of item
-
Service.update({'_id': req.params.service_id, 'shop._id': req.body.shop_id}, {$set: {"items.$.name": "yourValue","items.$.value": "yourvalue"}})
-
ParkingPlace.findOneAndUpdate({ '_id': req.params.service_id, 'branch_list': { $elemMatch: { 'shop_id': req.body.shop_id } } }, { $set: { 'branch_list.$.qty': req.body.value } }, { new: true }, function (err, service) { if (err) { res.json(err); } else { res.json(service); } }); 3.update multi Model.update({ _id : { $in : ids} }, { $set: {deletion_indicator: constants.N} }, { multi : true }, function(err, result) { if (err) { console.log(err); } else { console.log(result); } });
-
forEach Device.find(function(err, devices) { devices.forEach(function(device) { device.cid = ''; device.save(); }); });
-
Service_store.findOne({_id: req.body.service_store.id}, function(error, ser_get){ var set = {};
if(ser_get) set['qty_inventory'] = ser_get.qty_inventory*1 + req.body.service_store.qty_inventory*1; Service_store.findOneAndUpdate({ _id: req.body.service_store.id }, {$set: set}, function(error, service_store){ if(error){ res.json(error); }else{ res.json(service_store); } });
});
-
find multi condition: Store.find({region: "NA",sector:"Some Sector"}, function (err, stores) {})
-
-
increasing attribute up to number Model.findOneAndUpdate({ _id: res._id }, { $inc: { views: 1 } }, {new: true },function(err, response) { if (err) { callback(err); } else { callback(response); } ===========================================================2019/02/19 find with sort and limit Room.find({}, null, {sort: {date: -1}, limit: 30}, function(err, docs) { ... }); =======================================================2019/02/23 update object in array of a document Service.findOneAndUpdate( { code: reqService.code, "branch_list.shop_id": shopId }, { $inc: { "branch_list.$.sell": -reqQty } }, {}, function(error, ser_get){ if(error){ res.json(error); }else{ res.json(ser_get); } }); ===================================================================20190307 update field in array app.post('/api/update_bill_action', function(req, res) { Room.findOne({_id: req.body.id}, function(error, room){ if(error){ res.json(error); } else if(room == null){ res.json('no such sevice!') } else{ room.bill.forEach(function (service, index) { service.action = 'finish'; room.markModified('bill.' + index); }); room.save( function(error, data){ if(error){ res.json(error); } res.json(data); }); } }); }); ====================================================================2019/03/10 sort, skip, limit var queries = req.query.data; var pageNumber = parseInt(req.query.pageNumber); var limit = parseInt(req.query.limit); Service.find(queries, null, {sort: {create: -1}, limit: limit, skip: pageNumber*limit}, function(err, services) { // if there is an error retrieving, send the error. nothing after res.send(err) will execute if (err){ res.send(err) }else { res.json(services); } }); =============================================================2019/03/14 aggregate var dataFilter = [ { "$project": { name : 1, _id : 1, create : 1, name : 1, img : 1, code : 1, price : 1, price_mua : 1, price_chiphi : 1, price_von : 1, price_si : 1, qty : 1, sell : 1, sell_tam : 1, ncs : 1, supplier: 1, category : 1, status : 1, date_expire : 1, unit : 1, qty_inventory: { "$subtract": [ "$qty", "$sell" ] } }}, { "$match": { "qty_inventory": { "$gt": 10 } }}, ]; Model.aggregate(dataFilter, function (err, tests){ }); ==================================================2019/03/16 get all services follow search, pagination // get 30 services sellest app.get('/api/services_sellest', function(req, res) { // use mongoose to get all services in the database Service.find({}, null, {sort: {sell: -1}, limit: 30}, function(err, services) { // if there is an error retrieving, send the error. nothing after res.send(err) will execute if (err) res.send(err) res.json(services); // return all services in JSON format }); });
// get all services follow search, pagination app.get('/api/services_query', function(req, res) { // use mongoose to get all services in the database function replace_all(pStr='') { var str = pStr; str = str.toLowerCase(); str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g, "a"); str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, "e"); str = str.replace(/ì|í|ị|ỉ|ĩ/g, "i"); str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, "o"); str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u"); str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y"); str = str.replace(/đ/g, "d"); return str; } function isEmpty(obj) { for(var key in obj) { if(obj.hasOwnProperty(key)) return false; } return true; }
var queries = req.query.data; queries = JSON.parse(queries); // console.log(queries); var pageNumber = parseInt(req.query.pageNumber - 1); var limit = parseInt(req.query.limit); var dataFilter = [ { "$project": { name : 1, _id : 1, create : 1, name : 1, img : 1, code : 1, price : 1, price_mua : 1, price_chiphi : 1, price_von : 1, price_si : 1, qty : 1, sell : 1, sell_tam : 1, ncs : 1, supplier: 1, category : 1, status : 1, date_expire : 1, unit : 1, qty_inventory: { "$subtract": [ "$qty", "$sell" ]} } }, { "$match": { } }, { "$sort": {"create": -1} }, { "$skip": pageNumber * limit }, { "$limit": limit } ]; var dataCount = [ { "$project": { name : 1, _id : 1, create : 1, name : 1, img : 1, code : 1, price : 1, price_mua : 1, price_chiphi : 1, price_von : 1, price_si : 1, qty : 1, sell : 1, sell_tam : 1, ncs : 1, supplier: 1, category : 1, status : 1, date_expire : 1, unit : 1, qty_inventory: { "$subtract": [ "$qty", "$sell" ]} } }, { "$match": { } }, { $count: "total" } ]; if(queries.quantityExpire && queries.quantityExpire != -1) { if(queries.quantityExpire == 0) { dataFilter[1]["$match"]["qty_inventory"] = {"$lte": 0}; dataCount[1]["$match"]["qty_inventory"] = {"$lte": 0}; }else { dataFilter[1]["$match"]["qty_inventory"] = {"$lte": queries.quantityExpire, "$gt": 0}; dataCount[1]["$match"]["qty_inventory"] = {"$lte": queries.quantityExpire, "$gt": 0}; } } if(queries.dateExpire && queries.dateExpire != '') { } if(queries.name && queries.name != '') { queries.name = replace_all(queries.name); dataFilter[1]["$match"]["name"] = { $regex: '^.*' + queries.name + '.*$', $options:'i' }; dataCount[1]["$match"]["name"] = { $regex: '^.*' + queries.name + '.*$', $options:'i' }; } if(queries.code && queries.code != '') { queries.code = replace_all(queries.code); dataFilter[1]["$match"]["code"] = { $regex: '^.*' + queries.code + '.*$', $options:'i' }; dataCount[1]["$match"]["code"] = { $regex: '^.*' + queries.code + '.*$', $options:'i' }; } if(queries.categoryCode && queries.categoryCode != '') { queries.categoryCode = replace_all(queries.categoryCode); dataFilter[1]["$match"]["category.code"] = { $regex: '^.*' + queries.categoryCode + '.*$', $options:'i' }; dataCount[1]["$match"]["category.code"] = { $regex: '^.*' + queries.categoryCode + '.*$', $options:'i' }; } if(queries.supplierCode && queries.supplierCode != '') { queries.supplierCode = replace_all(queries.supplierCode); dataFilter[1]["$match"]["supplier.code"] = { $regex: '^.*' + queries.supplierCode + '.*$', $options:'i' }; dataCount[1]["$match"]["supplier.code"] = { $regex: '^.*' + queries.supplierCode + '.*$', $options:'i' }; } if(queries.date && queries.date != null && !isEmpty(queries.date)) { if(queries.date.start != '' && queries.date.start != null && queries.date.end != '' && queries.date.end != null) { var dateStartTmp = new Date(queries.date.start); dateStartTmp.setHours(0); dateStartTmp.setMinutes(0); dateStartTmp.setSeconds(1); var compStart = dateStartTmp.getTime(); var dateEndTmp = new Date(queries.date.end); dateEndTmp.setHours(23); dateEndTmp.setMinutes(59); dateEndTmp.setSeconds(59); var compEnd = dateEndTmp.getTime(); dataFilter[1]["$match"]["create"] = {"$gte": compStart, "$lte": compEnd}; dataCount[1]["$match"]["create"] = {"$gte": compStart, "$lte": compEnd}; } } // console.log(dataFilter); // console.log(dataCount); Service.aggregate(dataFilter, function(err, services) { // if there is an error retrieving, send the error. nothing after res.send(err) will execute if (err){ res.send(err) }else { Service.aggregate(dataCount, function(err, items) { if (err){ res.send(err); }else { if(items.length > 0) { res.json({data:services, total: items[0].total}); }else { res.json({data:services, total: 0}); } } }); } });
}); ======================================================count and modify return data async.waterfall([ function(callback) { // use mongoose to get all categorys in the database Category.find({"shop._id": shopParam.shop_id}, function(err, categorys) { // if there is an error retrieving, send the error. nothing after res.send(err) will execute if (err) { callback(null, err); }else { callback(null, categorys); } }); }, function(categorys, callback) { async.waterfall([ function(callback) { categorys.forEach(function(category, idx) { var dataCount = [ { "$project": { _id : 1, category : 1 } }, { "$match": { "category._id": { $regex: '^.' + category._id + '.$', $options:'i' } } }, { "$count": "total" } ]; Service.count({"category._id": category._id}, function(err, items) { if (err){ res.send(err); }else { category.count_services = items; categorys[idx].isModified('count_services'); if(idx == (categorys.length -1)) { callback(null, 'done'); } } }); }); } ], function (err, done) { callback(null, categorys); }); } ], function (err, result) { res.json(result); });