I am making a MEAN Stack application, and am attempting to create a database of businesses- which requires an empty array to push new instances of the Business model into.
I then want to sort the index of the businesses based on two of the keys- "name" (alphabetically) and "upVotes".
Here is what I have in my business.service file (client side):
var service = {
create: create,
businesses: [],
upVote: upVote,
showAllBiz: showAllBiz,
};
function showAllBiz(){
$http.get("/api/businesses")
.then(function(res) {
service.businesses = res.data;
}, function(err) {
$log.info(err);
});
}
function create(data) {
return $http({
method: 'POST',
url: '/api/businesses',
data: data,
headers: {
'Content-Type': 'application/json'
}
}).then(function(res) {
service.businesses.push(res.data);
});
}
I also tried to sort() on the back end, with no results. Here is what that looks like:
var Business = require("../models/business");
var nodemailer = require("nodemailer");
var transporter = nodemailer.createTransport();
var firstBy = require("thenby");
function index(req, res) {
if(req.query.search){
Business.find({}).then(function(data) {
var reg = new RegExp(req.query.search, "i");
data = data.filter(function(biz) {
if(reg.test(biz.name)) return biz
})
res.json(data);
}, function(err) {
res.json(err);
});
} else{
Business.find({}).then(function(data) {
res.json(data);
}, function(err) {
res.json(err);
});
}
}
function create(req, res) {
var business = new Business();
console.log(req.body);
business.name = req.body.name;
business.address1 = req.body.address1;
business.address2 = req.body.address2;
business.email = req.body.email;
business.twitterHandle = req.body.twitterHandle;
business.upVote = req.body.upVote;
business.save(function(err, savedBusiness) {
if (err) {
res.send(err)
}
res.json(savedBusiness);
});
I am getting stuck on the fact that I need the empty array for the new instances (in my services), but I also need to make use of the objects within the array in the .sort() method to access the keys (which I would like to sort).
I played with Teun's thenBy.js but was a bit out of my depth.
I have googled sorting arrays and arrays of objects, but these are all examples of sorting information that exists, not information that does not yet exist, thus necessitating the empty array.
:-). In case you're not aware, editors will sometimes read a post and trim non-essential parts of it, and/or make it more readable. There wasn't much to fix here!