Sorting up updatedAt mongoDB - node.js

So on my webpage www.groupwrites.com I am showing an Index of stories in the "Read" page. These stories currently show in the order of which they were created (i.e the newest ones on bottom). I am trying to figure out how to display them with the most recently created/updated one first. I am using mongoDB, node JS on cloud9. I have been trying to research and know that I should use updatedAt but I am not sure how to plug everything in. I am not sure how to update the timestamp for updatedAt in the put routes.
This is my code for the index:
// INDEX - show all stories
router.get("/browse", function(req, res, next){
// Get all stories from DB
Story.find({}, function(err, allStories){
if (err) {
return next(err);
} else {
// if user is logged in then render stories and any alerts
if(req.user) {
User.findById(req.user._id).populate({
path: 'alerts',
model: 'Alert',
match: { 'isRead': { $eq: false }}
}).exec(function(err, user) {
if(err) {
return next(err);
}
res.render("stories/index", {stories:allStories, alerts: user.alerts.length, page: 'browse'});
});
} else {
res.render("stories/index", {stories:allStories})
}
}
})
})
// CREATE - add new story to DB
router.post("/browse", middleware.isLoggedIn, function(req, res, next){
// get data from form and add to stories array
var title = req.body.title
var image = req.body.image
var desc = req.body.description
var category = req.body.category
var author = {
id: req.user._id,
username: req.user.username
}
var newStory = {title: title, image: image, description: desc, author: author, category: category}
// Create a new story and save to database
Story.create(newStory, function(err, newlyCreated){
if (err) {
return next(err);
} else {
// redirect back to stories page
req.flash("success", "Successfully published story!")
res.redirect("/browse")
}
})
})
This is the code for the content of the stories, (i.e when adding a chapter to the story):
// New Content
router.get("/stories/:id/content/new", middleware.isLoggedIn, function(req, res, next){
// Find story by id
Story.findById(req.params.id, function(err, story){
if (err) {
return next(err);
} else {
res.render("content/new", {story: story})
}
})
})
// Create Content
router.post("/stories/:id/content", middleware.isLoggedIn, function(req, res, next){
// Look up story using ID
Story.findById(req.params.id).populate({path: 'subscribors', model: 'User'}).exec(function(err, story){
if (err) {
return next(err);
} else {
Content.create(req.body.content, function(err, content){
if (err) {
return next(err);
} else {
if(story.subscribors.length) {
var count = 0;
story.subscribors.forEach(function(subscribor) {
// create alert for each subscribor and add to subscribor's alerts
Alert.create({follower: story.author.id, followed: subscribor, story: story, isUpdated: true}, function(err, newAlert) {
if(err) {
return next(err);
}
// console.log(newAlert);
subscribor.alerts.push(newAlert);
subscribor.save();
count+=1;
if(count === story.subscribors.length) {
// Add username and ID to content
content.author.id = req.user._id;
content.author.username = req.user.username;
// Save content
content.save();
story.content.push(content);
story.save();
req.flash("success", "Successfully added chapter!");
return res.redirect("/stories/" + story._id);
}
});
});
} else {
// Add username and ID to content
content.author.id = req.user._id;
content.author.username = req.user.username;
// Save content
content.save();
story.content.push(content);
story.save();
req.flash("success", "Successfully added chapter!");
return res.redirect("/stories/" + story._id);
}
}
});
}
});
});
// Content Edit Route
router.get("/stories/:id/content/:content_id/edit", middleware.checkContentOwnership, function(req, res){
Content.findById(req.params.content_id, function(err, foundContent){
if(err){
res.redirect("back")
} else{
res.render("content/edit", {story_id: req.params.id, content: foundContent})
}
})
})
// Content Update
router.put("/stories/:id/content/:content_id", middleware.checkContentOwnership, function(req, res){
Content.findByIdAndUpdate(req.params.content_id, req.body.content, function(err, updatedContent){
if(err){
res.redirect("back")
} else {
req.flash("success", "Successfully edited chapter!")
res.redirect("/stories/" + req.params.id)
}
})
})

While defining a Mongoose Schema,
1 for ascending and -1 for descending
Example:
"use strict";
var mongoose = require('mongoose');
var db= require('mongoose').models;
let findOrCreate = require('findorcreate-promise');
var abc= new mongoose.Schema({
name: String,
updated_At: { type: Date, default: Date.now } // like this you can define
});
mongoose.model('abc', abc);
and you can use this by :
db.abc.find({})
.sort({'updated_At':1}) //1 for ascending and -1 for descending
.exec(Your callback function)
this will make sorting from smallest updated_At date to largest.
Thanks

Related

How to update a data in mongodb using nodejs

I am trying to update a data in mongodb using nodejs. I want the total data to be updated by +1 once a user creates a transaction. But I don't have any idea of it. Because there is no value coming back. like req.body, that I can pass in.
var UserSchema = new mongoose.Schema({
total: { type: Number, default: 0 }
});
UserSchema.plugin(passortLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
app.post("/bitcoin", isLoggedIn, function(req, res) {
client.createTransaction({ currency1: "USD", currency2: "BTC", amount: 500 },
function(err, result) {
if (err) {
console.log(err);
} else {
User.findByIdAndUpdate(req.params.id, { total: +1 }, function(error,updated) {
if (error) {
console.log("error occured " + error);
return res.redirect("/dashboard");
} else {
console.log("total updated" + updated);
}
});
var coinPayment = result;
res.redirect(coinPayment.status_url);
}
}
);
});
It console.logs this below and it does not update any work around for this
total updated null
Try this, you have not declared id in params.
app.post('/bitcoin/:id',function(req, res){ /* Some stuff */})
Update Query
User.update({_id : req.params.id},{$inc: {total:1}})

How to delete Element In MongoDB property's array with MongooseJS?

I cannot remove an element inside of an array that is a property of a MongoDB Model.
Please remember this is a NodeJS module mongooseJS and not the real MongoDB so functionalities are not the same..
GOAL: Delete an object from the statusLiked array. | I have also confirmed that the value of status.id is correct.
Model:
Const userSchema = new mongoose.Schema({
myStatus: Array,
statusLiked: Array,
)};
Delete:
1. Deletes the status(works). 2. Delete the status from User.statusLiked(no work).
exports.deleteStatus = (req, res, next) => {
var CurrentPost = req.body.statusid; // sends in the status.id
Status.remove({ _id: CurrentPost }, (err) => {
if (err) { return next(err); }
// vvvv this vvv
User.update( {id: req.user.id}, { $pullAll: {_id: CurrentPost }, function(err) { console.log('error: '+err) } });
req.flash('success', { msg: 'Status deleted.' });
res.redirect('/');
});
};
What happens: The specific status(object) is deleted from the database. But the status still remains in the User.statusLiked array.
What I want to happen: Status to be deleted from the User.statusLiked array and the status to be deleted from the database. Then, reload the page and display a notification.
I got it to work somehow. Working code:
exports.deleteStatus = (req, res, next) => {
var CurrUser = req.body.userid;
var CurrentPost = req.body.post;
Status.remove({ _id: CurrentPost }, (err) => {
if (err) { return next(err); }
console.log('meeee'+CurrentPost+'user: ' +CurrUser);
req.flash('success', { msg: 'Status deleted.' });
res.redirect('/');
});
User.update(
{ _id: new ObjectId(CurrUser)},
{ $pull: { myStatus : { _id : new ObjectId(CurrentPost) } } },
{ safe: true },
function (err, obj) {
console.log(err || obj);
});
};

Updating a record with mongoose

I'm learning MEAN stack applications and am working on a tv watchlist app. I built the api successfully without the seasons field in the model. Now I'd like to add this field so that a user can add seasons and episodes to the document to keep track of episodes they have watched. Through trial and error I found the query I'd use in the mongo shell to update a field in the episodes object but I can't create the right syntax to do this with mongoose inside my route. Can someone look in my tele.js routes at the router.put and tell me what's wrong.
Models (TVSeries.js)
var mongoose = require('mongoose')
var Schema = mongoose.Schema
var tvSchema = new Schema({
title:String,
poster:String,
rated:String,
program_time:Number,
network:String,
airs_on:[],
streams_on:[],
genre:[],
seasons:[
season_number:Number,
episodes:[
{
episode_number:Number,
title:String,
watched:Boolean
}
]
]
}, {collection: 'tvShows'});
module.exports = mongoose.model('tv', tvSchema);
Routes (tele.js)
var express = require('express');
var router = express.Router();
var TV = require('../models/TVSeries.js');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Your Watchlist' });
});
router.get('/api/shows/:id/seasons', function(req, res){
TV.findById(req.params.id, 'seasons', function(err, data){
if(err){console.log(err)}
else{res.json(data)};
});
});
router.put('/api/shows/:id/seasons/:sid', function(req, res){
var setField = {
seasons:[
{
season_number:req.params.sid,
episodes:[
req.body
]
}
]
}
TV.findOneAndUpdate({"_id":req.params.id}, setField, {upsert:true}, function(err, results){
if(err){console.log(err)}
else{
console.log(setField);
res.json(results)
}
})
})
module.exports = router;
Mongo Shell command
db.tvShows.update({"_id":ObjectId('######################')},{$set: {'seasons.1.episodes.1.title':'This is my title change'}})
You can use &elementMatch to find the desire season in the array, and in the setField object you can use the positional $ operator which identify the element matched in the query.
The problem is that if it doesn't find any season that match the season_number, the document will not be updated. In this case you can set another update query to add this season in the seasons array.
router.put('/api/shows/:id/seasons/:sid', function(req, res){
var query = {
"_id": req.params.id,
"seasons": {
$elemMatch: {
"season_number": req.params.sid
}
}
}
var setField = {
$addToSet: {
"seasons.$.episodes": req.body
}
}
TV.findOneAndUpdate(query, setField, {upsert:true}, function(err, results){
if (err && err.code == 16836) { // no document was matched
var season = {
"season_number": req.params.sid
"episodes": [ req.body]
}
TV.findOneAndUpdate({"_id": req.params.id}, {$push: {"seasons": season}} , function(err, result) {
console.log("Inserted document in array");
res.json(result)
});
}
else if (err){
console.log(err);
res.status(500).send('Something wrong!');
}
else {
console.log(setField);
res.json(results)
}
})
})
You can see here some mongodb array operators.
Hope it helps.

RESTful API singular route with a single object to retrive and update (options parameters)

Hi i'm stucked trying to create a route in the RESTful API server in express.
I've configured other routes and now i need to configure an ('/options) or ('/profile') singular route where there is only one object to retrive and update.
Basically i need to do the same of the json-server module in the Singular routes section.
So when i visit the /options endpoint i got the predefined object with this schema
{
tax: Number,
inps: Number,
ritenuta: Number,
banca: {
nome: String,
iban: String
}
}
to update.
Here's my actual routes for /options:
var Option = require('../models/option');
var express = require('express');
var router = express.Router();
router.route('/options')
.get(function(req, res) {
Option.find(function(err, options) {
if (err) {
return res.send(err);
}
res.json(options);
});
})
.post(function(req, res) {
var option = new Option(req.body);
option.save(function(err) {
if (err) {
return res.send(err);
}
res.send({message: 'Option Added'});
});
});
// Save an option
router.route('/options/:id').put(function(req, res) {
Option.findOne({ _id: req.params.id}, function(err, option) {
if (err) {
return res.send(err);
}
for (prop in req.body) {
option[prop] = req.body[prop];
}
option.save(function(err) {
if (error) {
return res.send(err);
}
res.json({message: 'Option updated!'})
});
});
});
// Retrive an option
router.route('/options/:id').get(function(req, res) {
Option.findOne({ _id: req.params.id }, function(err, option) {
if (err) {
return res.send(error);
}
res.json(option);
});
});
// Delete an option
router.route('/options/:id').delete(function(req, res) {
Option.remove({ _id: req.params.id}, function(err, option) {
if (err) {
return res.send(err);
}
res.json({message: 'Option deleted!'});
});
});
module.exports = router;
but it's much complicated. It should be simpler. In fact, in this case i need to get all the options, get the id of options[0] and make a call with the id as params to retrive the object and update.
Any suggestions please?

What is the simplest and/or best way to send data between routes in node.js express?

My setup is like this:
I get data from omDB using a omdb lib from github, this whole parts looks like this:
router.post('/search', function(req, res) {
var omdb = require('omdb');
var title = req.body.title;
omdb.get( {title: title}, true, function(err, movie){
if(err) {
return console.log(err);
}
if(!movie) {
return console.log('No movie found');
}
//console.log('%s (%d)', movie.title, movie.year);
result = movie.title+movie.year+movie.poster;
console.log(result);
res.redirect('/result');
})
});
And then i want to use the result from that post request in another route:
router.get('/result', function(req, res) {
res.render('result', { title: title});
});
What is the best and hopefully simplest approach to do this, consider that I am a node.js noob.. :)
Assuming you're using express.js, you could use the session middleware:
router.post('/search', function(req, res) {
var omdb = require('omdb');
var title = req.body.title;
omdb.get( {title: title}, true, function(err, movie){
if(err) {
return console.log(err);
}
if(!movie) {
return console.log('No movie found');
}
//console.log('%s (%d)', movie.title, movie.year);
req.session.result = {
title: movie.title,
year: movie.year,
poster: movie.poster
};
res.redirect('/result');
})
});
then:
router.get('/result', function(req, res) {
if (req.session.result) {
var result = req.session.result;
req.session.result = null;
res.render('result', { movie: result });
}
else {
// Redirect to error page.
}
});

Resources