How to get the last inserted _id from MongoDB using node express - javascript

I am trying to get the lastly inserted _id from a MongoDB document. I am not sure how to do this, here is what I tried.
I need to send the _id using res.status(200).send(id)
Here is what I tried so far...
router.route("/last/inserted/assignment/id").get((req, res) => {
AssignmentDB.find({})
.sort({ _id: -1 })
.limit(1);
});

You can do this by getting a document according to when it was created...
router.get("/last/inserted/assignment/id", (req, res) => {
AssignmentDB.findOne().sort({createdAt: -1}).exec(function(err, post) {
if (err) {return err}
console.log(post)
});
Also NOTE The other mistake I've correctd in your code. You should correct that too.

Related

Trying to delete using Node.js Mongoose

app.delete("/tm/v1/tasks", (req,res) => {
Task.findOneAndDelete(req.body.id, (err, car) => {
if (err){
res.status(500).json({msg: error});
}
res.status(200).json({tasks});
})
});
The above isn't working and is giving an error 404. any ideas?
please check if you have are using correct url
we can add body to delete request in postman or curl but its not possible to pass body in javascript, dart (http package), etc.
you can rewrite function as
app.post('/tm/v1/delete-tasks', (req, res) => {
// write your code here...
});

Dynamic express.js routes based on database entries with no restart

I've build an KeystoneJS v5 app with a custom Express instance to serve data.
My data is stored in a Postgres database which contains the following model :
CREATE TABLE "Link" (
id integer DEFAULT PRIMARY KEY,
customer text,
slug text
);
I have built dynamic routes based on slug attributes :
knex('Link').select('slug').then(function(result){
const data = result.map(x => x.slug)
data.forEach(url => {
express.get(`/${url}`, function (req, res) {
res.render('index');
})
});
});
Everything works as expected but I have to restart my node server each time I insert new slug in the Link table.
Do you know how to avoid this ?
Thanks!
This might not be the complete answer but here's something along the lines of what you're looking for.
Ensure we accept any slug on the route
I've used an async function to await the results from the DB
Render the index view (if the slug was found) or reply with a 404 if no entry was found within the table
Word of warning, I have not used keystoneJS or this knexjs package, so it might not be 100% correct, but should be a good example of what we're trying to achieve. I'm assuming knexjs rejects the promise if no results are found, but I'm not sure.
express.get(`/:slug`, async function (req, res) {
try {
const result = await knex('Link')
.where({ slug: req.params.slug })
.select('id');
return res.render('index');
} catch {
return res.status(404).send({ message: "Not found" });
}
});
If you're running an older version of Node.js, here's a version without async.
express.get(`/:slug`, function (req, res) {
knex('Link')
.where({ slug: req.params.slug })
.select('id')
.then((result) => {
return res.render('index');
})
.catch(() => {
return res.status(404).send({ message: "Not found" });
});
});

Update query not working - express nodejs postgresql

anyone can help me to find the problem ?
I've tried to update data in users table in postgres-db. This code doesn't sent error message or anything, when I tried to check code in Postman like this (see below) I got success message, but data in database doesn't change at all.
router.post('/testedit/:userid', (req, res) => {
let sql = 'UPDATE users SET firstname=$1, lastname=$2, position=$3, type=$4, isadmin=$5 WHERE userid=$6'
db.query(sql, [req.body.firstname, req.body.lastname, req.body.position, req.body.type, req.body.isadmin, req.params.userid], (err, data) => {
if (err) console.log(err);
res.json({
message: 'update success'
})
})
})

Mongoose query using req.body not returning correct data

I want to retrieve data from the database using the Mongoose Model.find() function, passing along whatever parameters I get from req.body as well as the parameter req.user._id as my query.
So far what I've done is put the req.user._id inside my req.body and then passing them to Post.find() as follows:
getUserPosts: function(req, res) {
req.body.user = "" + req.params.id;
var query = JSON.stringify(req.body);
Post.find(query, function(err, posts) {
if(err) return res.status(500).json({error: unknownError});
else if(posts) return res.status(200).json({posts});
});
}
The problem is; I keep getting data results that do not match the query I am sending. What could I possibly be doing wrong here?
Firstly... remove that JSON.stringify part. The query parameter requires key/value object comprising of field names (key) that should match with values specified. For example var query = { _id: req.body._id }.
Second... What is that req.body.user = req.params.id?
Final code:
getUserPosts: function(req, res) {
var query = { _id: req.params.id };
Post.find(query, function(err, posts) {
if(err) return res.status(500).json({error: unknownError});
else if(posts) return res.status(200).json({posts});
});
}
You defined that req.body.user = "" + req.params.id;
I don't know whether the params.id is the Post.user in the post.
Whatever, your req.body became {user: id}
I suggest you print out the object of req.body and see whether it exists in your Post model in mongodb.
Besides, in mongodb, the generated _id is an ObjectId instead of string. You are supposed to login to mongodb and understand the format of the data.
See the following example in mongo:
> db.Post.find({"_id":"5786d286ed4b71f473efbd99"})
// nothing
> db.Post.find({"_id":ObjectId("5786d286ed4b71f473efbd99")})
{ "_id" : ObjectId("5786d286ed4b71f473efbd99"), "created" : ISODate("2016-07-13T23:45:10.522Z") }

How to send json from nodejs server to client js file using Express and MongoDB

I am new to Nodejs and Express and want to search some results from mongoDB and show it on client browser, i can find the values from the mongoDB query but not able to send it to client js file,
It says doc is not defined, any help will be appreciated.
***app.js(Server)***
var bodyParser = require("body-parser");
var express = require("express");
var app = express();
var port = "8001";
var mongo= require('mongodb');
var mongoClient=mongo.MongoClient;
app.use(bodyParser.json());
app.use(express.static('public'));
app.get('/home', function(req, res) {
res.sendFile(__dirname + "/public/views/index.html");
});
app.listen(port, function() {
console.log("Server running at:" + port);
})
app.post("/response", function(req, res) {
var t = req.body;
mongoClient.connect("mongodb://localhost:27017/query", function(err,db){
cursor =db.collection('response').find({"name1":t.text},{"name2":1, "_id":0});
cursor.each(function(err, doc) {
if (doc != null) {
console.log(doc);
}
});
})
res.send(doc);
});
***index.js(Client Side)***
$.ajax({
url: '/response',
type:"POST",
contentType:"application/json; charset=utf-8",
complete: function(data) {
console.log(data.responseText);
alert(data.responseText);
}
});
doc is a variable local to your closure and therefore not available when you call res.send(doc).
In addition to that, you are iterating over all of your documents. You need to choose which one to return.
I recommend something like this:
cursor = db.collection('response').find({"name1":t.text},{"name2":1, "_id":0});
cursor.each(function(err, doc) {
if (doc != null) {
console.log(doc);
return res.json(doc); // return the first document found
}
});
Also note:
you should sanitize your data before passing it into the query
you shouldn't connect to the database on each request, instead set up mongo in the application context
you should check err to see if mongo returned an error before trying to iterate the cursor
EDIT:
To be more specific, the whole block should look like this:
app.post("/response", function (req, res) {
var t = req.body;
mongoClient.connect("mongodb://localhost:27017/query", function (err, db) {
if (err) {
return res.json(err);
}
db.collection('tweets').findOne({"name1": t.text}, {"name2": 1, "_id": 0}, function (err, doc) {
if (doc != null) {
console.log(doc);
return res.json(doc);
}
return res.sendStatus(404);
});
});
});
A few things:
cursor.each() has been deprecated in favour of cursor.forEach() assuming you're running a recent version of mongo
Your first line in a callback should be something like if (err) { console.error(err) } - at this point you'd probably see that your query is invalid:
Your query should probably look like .find({'name1': t.text, 'name2': 1, '_id': 0})
If you are referencing an auto-generated mongo ObjectID as _id, you have to use '_id': new mongo.ObjectID(<whatever string holds the _id>) in order for it to work. If you didn't specify an _id on creation, the automatically generated ObjectID will require this.
The mongo docs are great, highly recommend leafing through them for examples and which bits take which arguments and the options for all of them.
Consider using promises instead of callbacks to help tidy up. It's really easy with mongo - you just don't specify a callback function, and instead tack a .then(document => { ... }) on the end, and a single .catch(err => {console.error(err)}) will catch errors at the db, collection and cursor levels.
With jQuery, consider using .done(result => {...}) and .fail(err => { ... }) (aka promises) instead of complete for your ajax calls, and whatever you do, don't forget to attach an error handler. (I'm not even sure 'complete' is the right property, might depend on which jQuery you're using)
If you're doing an AJAX POST you should probably attach some data (and a dataType)to it. Otherwise you'll still get no records because req.body will be undefined or empty.
In the case of an error, you should be responding with res.status(500); res.end() at a minimum so you can tell when something has gone wrong on the server end.
To help along, console.log(req.body) right at the top of your function so you know what data is arriving.
Finally, if you intend on responding with JSON - use res.json(doc) instead of res.send(doc)

Categories

Resources