router.get('/deleteRecord/delete/:id', function(req, res){
db.collection('inventories').remove({_id: mongodb.ObjectID( req.params.id)}, (err, result) => {
if (err) return console.log(err)
console.log('Welcome to Delete Function');
res.redirect('deleteRecord');
});
});
handlebars: Delete
Gettting the ID back but record isn't being deleted
Try this
db.collection('inventories').find({_id: mongodb.ObjectID( req.params.id)}).remove()
Related
I have a task that requires me to delete some data in an array that is in a JSON file, using node/express. I want, when a delete request is made, to delete a specific item that matches a specific id in the array that is in the JSON file. I tried using the filter method, but it doesn't seem to work.
JS file:
var obj = { projects: []};
app.post('/', (req, res, next)=>{
let identifier = req.query.identify; //id of project
fs.readFile('webProjects.json', (err, data)=>{
if(err) throw err;
obj = JSON.parse(data);
obj.projects.push({id:identifier, game: req.query.project});
let json = JSON.stringify(obj);
fs.writeFile('webProjects.json', json, (err)=>{
if(err) throw err
console.log("updatedd")
})
})
})
/*when user sends delete request, delete specific data.*/
app.delete("/", (req, res, next)=>{
fs.readFile('webProjects.json', (err, data)=>{
console.log(data)
obj = JSON.parse(data);
obj.projects.filter((item)=>{
let url = req.query.identify;
return item.id !== url;
})
console.log(obj)
let json = JSON.stringify(obj);
fs.writeFile('webProjects.json', json, (err)=>{
if(err) throw err;
console.log(obj)
})
})
})
/*when user navigates to another page, we display the data of the resource*/
app.get('/:id', (req, res, next)=>{
fs.readFile('webProjects.json', (err, data)=>{
if (err) throw err
res.send(data);
})
})
/*we want to catch all errors, with the requests made to the server.
used the wildcard(*) to make sure that we catch all requests made to the server.
*/
app.get('*', (req, res, next)=>{
let err = new Error('There was an error in accessing the page you wanted');
err.statusCode = 404;
next(err);
})
app.use((err, req, res, next)=>{
console.log(err.message)
if(!err.statusCode) err.statusCode = 500;
res.status(err.statusCode).send(err.message);
})
app.listen(8080, ()=>{
console.log("server has listened")
})
JSON file/data:
{"projects":[{"id":"1","game":"miniGame"},{"id":"2","game":"min"}]}
The filter function does not change the array so you need to assign the filtered items back to the array.
fs.readFile('webProjects.json', (err, data)=>{
console.log(data)
obj = JSON.parse(data);
// assign the filtered array back to the original array
obj.projects = obj.projects.filter((item)=>{
let url = req.query.identify;
return item.id !== url;
})
console.log(obj)
let json = JSON.stringify(obj);
fs.writeFile('webProjects.json', json, (err)=>{
if(err) throw err;
console.log(obj)
})
})
app.post('/profile', function(req, res) {
// save file
if (req.files) {
let sampleFile = req.files.sampleFile;
sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
if (err)
return res.status(500).json(err);
});
}
// do some other stuff
// .............
res.status(200).json(result);
});
I know the problem is caused by return res.status(500).json(err). I can solve the problem by moving res.status(200).json(result) after if (err) block. Since upload file is optional, the user may posting other data without any uploading files. My question is how to send status 200 with a json result after processed other stuff if the solution is
if (err)
return res.status(500).json(err);
res.status(200).json(result);
As was pointed above the problem is you are sending the success reponse outside of the callback.
The solution is to do "other stuff" within the callback.
This should fix the issue -
app.post('/profile', function(req, res) {
// save file
if (req.files) {
let sampleFile = req.files.sampleFile;
sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
if (err) return res.status(500).json(err);
doOtherStuff();
res.status(200).json(result);
});
} else {
doOtherStuff();
res.status(200).json(result);
}
});
// Write a do other stuff function
function doOtherStuff() {
// do stuff
}
EDIT Adding answer with Promises to avoid code repetition.
function moveFile(file, somePlace) {
return new Promise((resolve, reject)=>{
file.mv(somePlace, function(err) {
if (err) return reject(err);
resolve();
});
});
}
app.post('/profile', function(req, res) {
// save file if present
const fileMovePromise = req.files ?
moveFile(req.files.sampleFile, '/somewhere/on/your/server/filename.jpg')
:
Promise.resolve('No file present');
fileMovePromise
.then(() => {
// do other stuff
})
.catch(err => {
res.status(500).json(err);
});
});
You could use a form of middleware to check if the post is uploading files, the act on the file upload before continuing, have a look at middleware with express here: http://expressjs.com/en/guide/using-middleware.html
With middleware you can do your check to see if the file needs uploading and then call next, otherwise just call next.
app.use('/profile', function (req, res, next) {
if (req.files) {
let sampleFile = req.files.sampleFile;
sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err, data) {
if (err) {
res.status(500).json(err);
} else {
req.data = data
next()
}
});
}
res.status(200);
}, function (req, res) {
res.status(500).json(req.data);
})
If you are using Node for express, the res param contains res.headersSent, which you can check if the headers have already been sent.
if(res.headersSent) {}
You can also find out a lot more here: https://nodejs.org/api/http.html#http_response_headerssent
A little background. I am sending a post with the username. About what he came to me is displayed in the log.
console.log(req.body.username); // 'username'
How do I use mongodb to find and render a user with a username from the post?
For example, the sample and render of all users looks like this, but I still do not understand how to get the one I need
exports.profile = function(req, res, next){
User.find(function(err,users){
if(err) return next(err);
res.render('users/profile',{ users:users });
});}
Try this
exports.profile = function(req, res, next){
User.find({username: req.body.username}function(err,users){
if(err) return next(err);
res.render('users/profile',{ users:users });
});}
and here you have some docs to read http://mongoosejs.com/docs/queries.html
Use findOne function to find.
User.findOne({username: req.body.username}.function(err,users){
if(err) return next(err);
res.render('users/profile',{ users:users });
});}
Hello I'm learning mongoDB and trying to print out my database query results to the browser.
I have a program working where it writes the output JSON to the console using console.log()
Is there a way to use res.send() (using express) or response.write() and response.send() to simply output the raw JSON data that the database query gets?
In other words, How can I make my database invokatation return a string?
// Use connect method to connect to the server
var invokeDatabase = function() {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to database server");
findDocuments(db, function() {
findDocumentsFiltered(db, function() {
db.close();
});
});
});
};
//routes
app.get('/', function(req, res) {
console.log("Someone connected.")
res.send("accessing database... " + invokeDatabase())
//res.send('Welcome G')
})
This example may help you to understand
// Use connect method to connect to the server
var invokeDatabase = function(callback) {
MongoClient.connect(url, function(err, db) {
//assert.equal(null, err);
if(err) {
console.log("Unable to connect database");
callback(err, null);
return;
}
console.log("Connected successfully to database server");
findDocuments(db, function() {
findDocumentsFiltered(db, function(err, data) {
callback(err, data);
db.close();
});
});
});
};
//Added for demo. Here users is collection
var findDocumentsFiltered = function(db, callback) {
db.collection('users').find({}).toArray(function(err, userList) {
callback(err, userList);
});
};
//routes
app.get('/', function(req, res) {
console.log("Someone connected.")
invokeDatabase(function(err, data) {
if(err)
res.status(500).json({error: err});
else
res.json(data);
}))
//res.send('Welcome G')
})
I have successfully set up a database using mongodb, and I have managed to add new entries to my collection. However, when I use a similar method to delete, nothing happens.
Express.js code
router.post('/deleteproject', function(req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/plugd';
MongoClient.connect(url, function(err, db) {
if (err) {
console.log("Unable to connect to server", err);
} else {
console.log('Connected to server');
var collection = db.collection('projects');
collection.remove(
{_id: new mongodb.ObjectID(req.body)}, function(err, result) {
if (err) {
console.log(err);
} else {
res.redirect("thelist");
}
db.close();
});
}
});
});
Jade code
h2.
ul
Projects
each project, i in projectlist
#project_list_item
a(href='#') #{project.owner} - #{project.project}
p #{project.ref1}
p #{project.ref2}
p #{project.ref3}
form#form_delete_project(name="deleteproject", method="post", action="/deleteproject")
input#input_name(type="hidden", placeholder="", name="_id", value="#{project._id}")
button#submit_project(type="submit") delete
I figured it out. Here is my fix for deleting data from a mongodb collection using a router in express.js.
Express.js
router.post('/deleteproject', function(req, res) {
var MongoClient = mongodb.MongoClient;
var ObjectId = require('mongodb').ObjectId;
var url = 'mongodb://localhost:27017/app';
MongoClient.connect(url, function(err, db) {
if (err){
console.log('Unable to connect to server', err);
} else {
console.log("Connection Established");
var collection = db.collection('projects');
collection.remove({_id: new ObjectId(req.body._id)}, function(err, result) {
if (err) {
console.log(err);
} else {
res.redirect("thelist");
}
db.close();
});
}
});
});
Jade code
extends layout
block content
h2.
Projects
ul
each project, i in projectlist
#project_list_item
a(href='#') #{project.owner} - #{project.project}
p #{project.ref1}
p #{project.ref2}
p #{project.ref3}
form#form_delete_project(name="deleteproject", method="post", action="/deleteproject")
input#input_name(type="hidden", placeholder="", name="_id", value="#{project._id}")
button#submit_project(type="submit") delete
The jade file is rendering to a page called 'thelist' that lists each item in the collection.
The form section handles the delete function for each item in the list.
This works for me as long as I keep Jade's indents happy :)
Try this and see if it works :
router.post('/deleteproject', function(req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/plugd';
MongoClient.connect(url, function(err, db) {
if (err) {
console.log("Unable to connect to server", err);
} else {
console.log('Connected to server');
var collection = db.collection('projects');
collection.remove(
{_id: req.body}, function(err, result) {
if (err) {
console.log(err);
} else {
res.redirect("thelist");
}
db.close();
});
}
});
});
Since you're on MongoDB's Node.js Native Driver, you don't need to marshall _id inside ObjectId. You can directly specify the _id as string