updated a document with express - javascript

I'm trying to use the mongoDB and update the status of a current document. My backend is receiving the routes my mongoDB update isn't going through.
router.post('/orders_drivers', function (req, res, next) {
console.log(req.body);
Order.update({_id:objectId(req.body.id)}, {$set: {driver:req.body.driver, driverReq:false}}).then (function (order) {
console.log('UPDATE new driver');
}).catch (next)
});
when I log the req.body, the ID I receive and the new $set parameters are correct, but the command never goes through. Any suggestions? I don't receive any errors either which I think is strange.
Mongo version is v4.0.2
I have many other routes that all work correctly.

There is no version issue. you are calling then function on non promiseable value.
You need to call a callback function inside of update.
const mongoose = require('mongoose');
router.post('/orders_drivers', function (req, res, next) {
console.log(req.body);
Order.update({
_id: mongoose.Types.ObjectId(req.body.id)
},
{
$set: {
driver:req.body.driver, driverReq:false
}
},
{ new: true }, // If you want to return updated order
function (err, updatedOrder) {
if (err) throw err;
console.log('UPDATE new driver', updatedOrder);
})
});
You don't need to convert req.body.id into mongoose ObjectId if it already is.

Related

Can't get data for req.body with mean stack

Hey I can't seem to get any results whilst using the req.body. Trying to get out the data from my mongodbdatabase to json format Here is my code:
My server file:
app.get('/api/category/posts', (req, res) => {
Post.find({ categoryId: req.body._id }, function(err, posts) {
res.json(posts);
});
});
Service file:
getPosts(_id): Observable<Post[]>{
return this.http.get<Post[]>(this.apiUrl +"/category/posts");
}
component.ts
this.appService.getPosts(_id)
.subscribe(data =>this.posts=data);
your api method is get method and you want _id in req.body. which is wrong.
you need to either change you get request to post in server file and service file both or try to pass _id in req.params or req.query:-
If you pass _id as req.query :-
your server code will be like:-
app.get('/api/category/posts', (req, res) => {
Post.find({ categoryId: req.query._id }, function(err, posts) {
res.json(posts);
});
});
service file
getPosts(_id): Observable<Post[]>{
return this.http.get<Post[]>(this.apiUrl +"/category/posts"+'?_id='+_id);
}
component.ts will be same.
and if you want to use post method to check for req.body then your code will be changed as following:-
your server code will be like:-
app.post('/api/category/posts', (req, res) => {
Post.find({ categoryId: req.body._id }, function(err, posts) {
res.json(posts);
}); });
service file
getPosts(_id): Observable<Post[]>{
return this.http.post<Post[]>(this.apiUrl +"/category/posts",{_id:_id});
}
component.ts will be same.
Following REST architecture to get resources, you should pass the the _id in the get request parameters. You can also validate your id parameter making sure the passed id is a number using a simple regex pattern
Express route
app.get('/api/category/posts/:id(\\d+)', (req, res) => {
Post.find({ categoryId: req.params.id }, function(err, posts) {
res.json(posts);
});
});
service file
getPosts(_id): Observable<Post[]>{
return this.http.get<Post[]>(`${this.apiUrl}/category/posts/${_id}`);
}
component file
this.appService.getPosts(_id)
.subscribe(data =>this.posts=data);
As a good practice, you should also keep track of your subscriptions and unsubscribe from them when you are done or on component destroy, or use the first operator to unsubscribe after first subscription.

res.redirect is not a function in express

I'm currently trying to redirect to an external site with node and express specifically in a get call. However, I can't seem to find a possible solution. Any help would be appreciated. Note that when trying response.redirect I'm getting TypeError: res.redirect is not a function. However, when I view the express documentation it seems to be in there.
app.get('/:urlToForward', (res, req, next)=>{
//Stores the value of param
// var shorterUrl = res.params.urlToForward;
// shortUrl.findOne({'shorterUrl': shorterUrl}, (err,data)=>{
// // if (err) {
// // res.send("This shorterUurl does not exist.");
// // }
// // else {
// // res.redirect(301, data.originalUrl);
// // }
// // response.end();
// });
res.redirect('https://www.google.com');
});
Order matters in the arguments. req must be first, then res, then next.
app.get('/:urlToForward', (req, res, next)=>{ ...
You can do res.redirect('http://app.example.io');
Express docs: http://expressjs.com/api.html#res.redirect
Just use simple:
app is instance of invoked Express application.
app.get('/', function(request,respond) {
respond.redirect('your_url'); //Pass between the brackets your URL.
});
Note you can use ES6 shorthand for shorterUrl, no need to type it out twice.
app.get('/:urlToForward', (req, res, next)=> {
//Stores the value of param
var shorterUrl = res.params.urlToForward;
shortUrl.findOne({shorterUrl}, (err, data)=> {
if (err) {
res.send("This shorterUrl does not exist.");
}
else {
res.redirect(data.originalUrl);
}
response.end();
})
});

Mongoose: .save is not a function

I'm very new and I've looked through the archives but just what's going on in this code eludes me. I used express-generator to create a calendar app and now I want to hook it up to MongoDB. The actual connection to Mongo is working, but I can't get it to save a document.
The relevant portion of my global.js (where I'm running my front-end Javascript) looks like this:
$(document).ready(function() {
var ev = new Event({ date: "a6_13_2016", time: 900, description:"Fencing"});
ev.save(function(err) {
if (err) console.log(err);
else console.log("Success!")
})
This is where I'm getting the "TypeError: ev.save is not a function" message. My models/Events.js looks like this:
var mongoose = require('mongoose');
var eventSchema = new mongoose.Schema({
date: String,
time: Number,
description: String
});
module.exports = mongoose.model('Event', eventSchema);
My routes/events.js looks like this:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Event = require('../models/Events.js');
/* GET /event listing. */
router.get('/', function(req, res, next) {
Event.find(function (err, dates) {
if (err) return next(err);
res.json(dates);
});
});
/*POST event*/
router.post('/', function(req, res, next) {
Event.create(req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* GET /event/id */
router.get('/:id', function(req, res, next) {
Event.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
module.exports = router;
I want to save something to test it, but it's giving me ".save is not a function. Other than
var events = require('./routes/events');
app.use('/events', events);
and the code establishing the Mongoose connection my app.js file is boilerplate. What do you think is the problem?
I see
$(document).ready(function() {
Are you trying to use Mongoose in browser?
It's supposed to be used on the server-side.
In browser you need to send AJAX request to the server:
$('#save').click(function() {
$.post('/event', function(response) { console.log(reposne) })
});
On the server you should add a route that will handle your AJAX request, and inside this route you can save your model:
router.post('/event', function(req, res) {
var ev = new Event({ date: "a6_13_2016", time: 900, description:"Fencing"});
ev.save(function(err) {
if (err) console.log(err);
else console.log("Success!")
})
});
Please note that you don't need the 3rd param next in your rotues. It is used only in middlewares
Are you sure that line
var Event = require('../models/Events.js');
has the correct path?
You are creating an ev object from Event function and it seems that ev is undefined, judging from the error description.
If your Event file is not properly loaded you will not have access to .save function.

Node.js async consistency

I have the following code :
server.use(function(req, res, next) {
users_db.set(req.user, function(err) { // async call to mongodb
if (err) {
console.error(err);
}
});
}
return next();
});
server.get('/', function(req, res) {
req.user.active = true; // this is a new field in user object
res.send(req.user);
}
});
So, As you see, when users_db.set() is called, req.user doesn't have the active=true field. It is being inserted only in the server.get() function.
Is it possible that user.active = true is registered in the db nevertheless because of the asynchronous nature of the call ?
As far as I know (it is like that in Express at least) .get method accepts many middleware functions. So I guess that the following will work:
server.get(
'/',
function(req, res, next) {
req.user.active = true; // this is a new field in user object
res.send(req.user);
next();
},
function(req, res, next) {
users_db.set(req.user, function(err) { // async call to mongodb
if (err) {
console.error(err);
}
});
}
return next();
}
);
Doing the things like that you are sure that req.user.active is populated always before to reach the moment with users_db.set.

Add data to session in nodejs express in a callback

In the below code i'm trying to fetch the user details from DB and save it to session. But unfortunately it doesn't work as i've expected, the data is not written into the session variable. I guess it's because of pass by value? Any workaround
exports.check = function(req,res,next){
..
..
getUserFromDB(req);
}
function getUserFromDB(req){
..
db.findOne(query,function(doc){
req.session.user = doc;
})
}
I think you are missing the callback call.
Are you using express and mongodb? We should post full working examples :)
exports.check = function (req, res, next) {
getUserFromDB(req, next);
};
function getUserFromDB(req, callback) {
db.findOne({ _id: req.qs.id }, function (err, doc) {
req.session.user = doc;
callback(err);
});
}
Also check for err, and also for null doc (not found).

Categories