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}})
Related
I am a noobie in coding and I am having an issue with how to use properly MongoDB. I have a parent object classroom containing an array of objects - comments. I am trying to update the content of 1 selected comment.
originally I updated the state of the whole "classroom" in the react and passed all the data and $set {req.body} in findByIdAndUpdate.
I want to achieve the same result if I only pass to my axios request classId, commentId and comment data and not whole classroom / all comments
I tried to filter selected comment out of the array of comments and concat updated comment, but that did not work. Clearly, I have any idea what is going on and docs don't make it any easier for me to understand.
my classroom schema:
var ClassroomSchema = new Schema({
title: String,
teacher: String,
info: String,
image_url: String,
comments: [Comment.schema]
});
comment schema:
var CommentSchema = new Schema()
CommentSchema.add({
content: String,
comments: [CommentSchema],
created_at: {
type: Date,
default: Date.now
}
});
original solution:
function update(req, res){
Comment.findById(req.params.comment_id, function(err, comment) {
if(err) res.send(err)
comment.content = req.body.content;
comment.save();
console.log(req.body.comments)
Classroom.findByIdAndUpdate(req.params.classroom_id,
{$set: req.body}, function(err, classroom){
if (err) {
console.log(err);
res.send(err);
} else {
commentToUpdate = req.body.commentData;
res.json(classroom);
}
});
});
}
my current failing atempt:
function update(req, res){
console.log('update => req.body: ', req.body);
console.log('req.params', req.params)
Comment.findById(req.params.comment_id, function(err, comment) {
if(err) res.send(err)
comment.content = req.body.content;
comment.save();
console.log('comment: ', comment);
Classroom.findById(req.params.classroom_id, function(err, classroom) {
console.log('CLASSROOM findByIdAndUpdate classroom: ', classroom)
// console.log('reg.body: ', req.body)
if (err) {
console.warn('Error updating comment', err);
res.send(err);
} else {
// commentToUpdate = req.body.commentData;
old_comments = classroom.comments;
console.log('comments: ', old_comments);
Classroom.findByIdAndUpdate(req.params.classroom_id,
{$set:
{ comments: old_comments.filter(comt._id !== comment._id).concat(comment)}
}, function(err, updatedClassroom) {
if (err) {
console.warn(err);
} else {
res.json(updatedClassroom);
}
});
}
});
});
}
haven't tested, but try this.
function update(req, res) {
Classroom.update(
{ _id: req.params.classroom_id, "comments._id": req.params.comment_id },
{ $set: { "comments.$.content": req.body.content } },
function(err) {
..
}
);
}
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
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);
});
};
This is my controller, one form send here the data:
exports.addrepair = function(req, res, next){
Person.findById( req.body.id, function (err, Person) {
Person.update({id: req.body.id},
{$pushAll: {
problem: req.body.problem
, solution: req.body.solution
, date_on: Date.now()
}}
,{upsert:true},function(err){
if(err){
console.log(err);
}else{
console.log("Added");
}
})
})
}
the schema is:
var Person = new Schema ({
name: String,
Repair: [
problem: String,
solution: String,
date_on: Date
]
})
and cant push any repair to Person. With console.log i can see all works but not the push.
This works for me now. Thanks Peter Lyons
Person.findByIdAndUpdate(req.body.id,
{ $push:
{ repair:
{ problem: req.body.problem
, solution: req.body.solution
, date_on: Date.now()
}
},
function(err){ if(err){
console.log(err)
} else {
console.log('Added')
}
});
exports.addrepair = function(req, res, next) {
//The Person.findById you had here was unnecessary/useless
Person.findByIdAndUpdate(req.body.id,
{
Repair: {
$push: {
problem: req.body.problem,
solution: req.body.solution,
date_on: Date.now()
}
}
},
//You don't want an upsert here
function(err){
if(err){
console.log(err);
}else{
console.log("Added");
}
}
)
}
I'm trying to update an existing record with Mongoose. The insert is OK but not the update.
Here is my snippet:
app.post('/submit', function(req, res) {
var my_visit = new models.visits({
date: req.body.visit_date,
type: req.body.visit_type,
agency: req.body.visit_agency,
city: req.body.visit_city,
url: req.body.visit_url,
note: req.body.visit_note
});
// INSERT
if(req.body.id == 0) {
my_visit.save(function(err) {
if(err) { throw err; }
console.log('added visit');
res.redirect('/');
});
} else { // UPDATE
var upsertData = my_visit.toObject();
console.log(req.body.id); // OK
models.visits.update({ _id: req.body.id }, upsertData, { multi: false }, function(err) {
if(err) { throw err; }
console.log('updated visit: '+ req.body.id);
res.redirect('/');
});
}
})
The response is Mod on _id is not allowed.
I just want to update the line such as WHERE id = id in MySQL. I didn't find the right syntax.
According to this question and this other one, the Mod on _id is not allowed occurs when one tries to update an object based on its id without deleting it first.
I also found this github issue which tries to explain a solution. It explicitly states:
Be careful to not use an existing model instance for the update clause
(this won't work and can cause weird behavior like infinite loops).
Also, ensure that the update clause does not have an _id property,
which causes Mongo to return a "Mod on _id not allowed" error.
The solution, it seems, is to do the following:
var upsertData = my_visit.toObject();
console.log(req.body.id); // OK
delete upsertData._id;
models.visits.update({ _id: req.body.id }, upsertData, { multi: false }, function(err) {
if(err) { throw err; }
//...
}
On a side note, you can probably rewrite your route to do both the create and update without the if-else clause. update() takes an extra option upsert, which, according to the docs:
upsert (boolean) whether to create the doc if it doesn't match (false)
Here is my solution:
routes/router.js
router.patch('/user/:id', userController.updateUser)
exports.updateUser = async(req, res) => {
const updates = Object.keys(req.body)
const allowedUpdates = ['name', 'email', 'password', 'age']
const isValidOperation = updates.every((update) => allowedUpdates.includes(update))
if (!isValidOperation) {
return res.status(400).send('Invalid updates!')
}
try {
const user = await UserModel.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true })
if (!user) {
return res.status(404).send()
}
res.status(201).send(user)
} catch (error) {
res.status(400).send(error)
}
}