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");
}
}
)
}
Related
I am struggling to get .put or .patch to work. when using postman I get the call back returned but the values are not updated in my database on robo 3t. I have tried fixing the deprecation warning and using updateOne, updateMany.
This will fix the deprecation warning but will not update the database. Here is the code before i fix the deprecation. Any ideas what I'm doing wrong?
////////////////////Request Targeting A Specific Article///////////////////////
app.route("/articles/:articleTitle")
.get(function(req, res){
Article.findOne({title: req.params.articleTitle}, function(err, foundArticle){
if (foundArticle) {
res.send(foundArticle);
} else {
res.send("No articles with that title.");
}
});
})
/////////PUT PROBLEM MUST BE FIXED /////////////
.put(function(req, res){
Article.update(
{title: req.params.articleTitle},
{title: req.body.title, content: req.body.content},
{overwrite: true},
function(err){
if(!err){
res.send("succesfully updated");
}
}
);
})
///////PATCH PROBLEM MUST BE FIXED ///////////
.patch(function(req, res){
Article.update(
{title: req.params.articleTitle},
{$set: req.body},
function(err){
if(!err){
res.send("Successfully updated article.");
} else{
res.send(err);
}
}
);
});
app.route("/articles/:articleTitle")
.get((req, res) => {
Article.findOne({ title: req.params.articleTitle }, (err, result) => {
if (result) {
res.send(result);
} else {
res.send("err");
}
});
})
.put((req, res) => {
Article.replaceOne(
{ title: req.params.articleTitle },
{ title: req.body.title, content: req.body.content },
{ overwrite: true },
(err) => {
if (err) {
res.send("There is some error");
} else {
res.send("Updated successfully");
}
}
);
})
.patch((req, res) => {
Article.updateOne(
{ title: req.params.articleTitle },
{ $set: req.body },
(err) => {
if (err) {
res.send("There is some error");
} else {
res.send("Updated successfully");
}
}
);
});
Try this!! this will work fine.
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) {
..
}
);
}
i am posting an object to update the current one. Searching by id and replacing it. For some reason i don't get errors but the mlab object is not updated. Am i missing something?
app.post("/api/updateCheck", function (req, res) {
console.log('updating', req.body);
conn.collection("checks").findAndModify({
_id: req.body._id
}, {$set: req.body}, {}, function(err,doc) {
if (err) { console.log(err) }
else { console.log("Updated"); }
});
});
got it. updateOne seems to work. I am posting a check object and retrieving id from it to search the collection and update content accordingly.
// modify content
app.post("api/updateCheck", function(req, res) {
console.log("updating", req.body);
conn.collection("checks").updateOne(
{
_id: new ObjectId(req.body._id)
},
{
$set: {
content: req.body.content
}
},
function(err, doc) {
if (err) {
console.log("error", err);
} else {
console.log('success', doc.modifiedCount);
console.log('??', doc.matchedCounted);
res.status(200).json(res.body);
}
}
);
});
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}})
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);
});
};