I'm' trying to create a 'groupe' and then insert its creator as administrator in 'groupemembers' table, however the second query gets skipped
router.post('/createGroupe/:userId', upload.single('file'), (req, res) => {
let groupe = req.body
// req.body containing the groupe title, description
let userId = req.params.userId
let groupeId
groupe['image'] = req.file
db.query('insert into groupes set ?', groupe, function(err, result){
if (err) throw err;
groupeId = result.insertId.toString()
db.query("insert into groupemembers set ?", [groupeId, userId, 'admin'], function (err, result){
console.log(groupeId)
if (err) return err;
})
res.send(result.insertId.toString())
})
})
you need to learn callback style or even better async/await style. much more easier to code.
but for your specific concern, i think you wanted to put the res.send one line up
because that way you will call res.send AFTER the second query has executed.
router.post('/createGroupe/:userId', upload.single('file'), (req, res) => {
let groupe = req.body
// req.body containing the groupe title, description
let userId = req.params.userId
let groupeId
groupe['image'] = req.file
db.query('insert into groupes set ?', groupe, function(err, result){
if (err) throw err;
groupeId = result.insertId.toString()
db.query("insert into groupemembers set ?", [groupeId, userId, 'admin'], function (err, result){
console.log(groupeId)
if (err) return err;
res.send(result.insertId.toString())
})
})
})
Related
app.post('', (req, res) => {
pool.getConnection((err, connection) => {
if (err) throw err
console.log('connected as id' + connection.threadID)
const params = req.body;
connection.query('INSERT INTO beers SET ?', [params], (err, rows) => {
connection.release()
if (!err) {
res.send('Successfully added record of name' + params.name)
} else {
console.log(err)
}
})
console.log(req.body)
})
})
I'm not sure what kind of library you're using to communicate with the DB, but I reckon, it should look more like
connection.query('INSERT INTO beers(someColumn, someOtherColumn) VALUES (?,?)', [params.valueOfSomeColumn, params.valueOfSomeOtherColumn],...blabla the rest)
Looks like you're mixing up the INSERT and UPDATE statements. INSERT doesn't use SET
Usually this sort of basic DB libs connect the ? characters with the value from an array
I have problems with the REST API.
I have a file named route. In which I make a request that is then passed to the server where it is called. In my third request, I want to select an ID to pass it as an API and write to call the page inside/:id, but I only get an error (This is a POST request)
const post_inside = (req, res) => {
var config = {
user:'postgres',
database:'my',
password: '1',
host:'localhost',
port:5432,
max:10,
idleTimeoutMillis: 30000
}
var pool = new pg.Pool(config)
pool.connect(function(err, client, done){
if(err){
return console.error('error')
}
client.query("SELECT *,to_char(data_roz::date , 'YYYY-MM-DD') as data_roz from sch.idv_p where phone=$1",[req.body.login], function(err, result){
done()
return_data.pupil2 =result
if (err) {
res.end()
return console.error("error")
}
client.query('select * from table1 ($1,$2)',[req.body.login,req.body.date], function(err, result){
return_data.discipline =result
if (err){
res.end()
return console.error("error")
}
//3 HERE
client.query("select id from table3 where phone=$1",[req.body.login], function(err, result){
return_data.id =result
if (err){
res.end()
return console.error("error")
}
res.render('inside/:id',{pupil2:return_data.pupil2,discipline:return_data.discipline,id:return_data.id})
})})}}
module.exports = {
post_inside
}
server:
app.post('/inside/:id',urlencodedParser,db.post_inside)
I want to call the same file, but for example as inside/2555
I am trying to return all the details of the product and display them in table format
I have already tried this in my api
app.get('/test',(req,res) => {
const client = new Client({
connectionString: connectionString
})
client.connect()
client.query('select * from product',(err,res) =>{
console.log(err,res)
if(err){
console.log(err);
}else{
console.log(res);
}
client.end()
})})
How do i return this res in node?
You are hiding the outside res in the route handler with the inside res of the query result.
I have to make some assumptions about your query client, but if the inside res is the array of rows, simply pass it to the res.json() function (another assumption is you are using Express).
My suggestion:
app.get('/test', (req, res) => {
const client = new Client({
connectionString: connectionString
})
client.connect()
client.query('select * from product', (err, rows) => {
console.log(err, rows)
if (err) {
console.log(err);
} else {
console.log(rows);
res.json(rows);
}
client.end()
})
});
Tried this for updating user information , only phone number but it's not getting update.
router.post('/edit', checkAuth, function (req, res, next) {
console.log(req.userData.userId)
User.update({_id: req.userData.userId}, {$set:req.userData.phoneNo}, function (err){
if (err) {
console.log(err);
}
res.status(200).send(req.userData);
});
});
My user controller const mongoose = require ('mongoose');
const User = mongoose.model('User');
module.exports.register = (req, res, next) =>{
var user = new User();
user.fullName = req.body.fullName;
user.email = req.body.email;
user.password = req.body.password;
user.phoneNumber = req.body.phoneNumber;
user.save((err, doc) =>{
if(!err)
res.send(doc);
else{
if (err.code == 11000)
res.status(422).send(["Entered duplicate email address. Please check"]);
else
return next(err);
}
});
}
And then I am authenticating by passing jwt on this field
phoneNo: user[0].phoneNumber
The auth-token verifies and decode the fields
const token = req.headers.authorization.split(" ")[1];
const decoded = jwt.verify(token, process.env.JWT_KEY)
req.userData = decoded;
Update is not working and getting error message Invalid atomic update value for $set. Expected an object, received string .
first of all, you should use PATCH-method - because you are updating only one item in existed object, in body you should send id of user and new value of certain value. If you use mongoose you can try it
User.findOneAndUpdate({ _id: id }, updatedItem, { new: true }, (err, doc) => {
if (err) return res.send(err.message)
if (doc) return res.send(doc);
})
const id = req.body._id;, if you dont use mongoose you should try findAndModify method
Your code
User.update({_id: req.userData.userId}, {$set:req.userData.phoneNo}
Correct code:
User.update({_id: req.userData.userId}, {$set:{phoneNumber:req.userData.phoneNo}}
Try this method:
User.findByIdAndUpdate(req.userData.userId, { $set:{phoneNumber:req.userData.phoneNo}}, { new: true }, function (err, user) {
if (err) console.log(err);
res.send(user);
});
Can you please help me with this code. This code is not deleting the value from MongoDB, while I am running this url : http://localhost:3000/delete/57c6713455a6b92e105c5250.
I am getting this response: {"lastErrorObject":{"n":0},"value":null,"ok":1}, but not deleting .
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
db.collection('quotes').findOneAndDelete({'_id': uid}, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});
In MongoDB you query a document id(_id) by using the ObjectId constructor and not the ObjectId's string. Thus the query needs to be: { '_id': ObjectId(uid) }.
Example
var mongoClient = require('mongodb').MongoClient;
//Include ObjectId
var ObjectId = require('mongodb').ObjectID;
mongoClient.connect("Your connection string", function(err, db) {
var query = {
_id: ObjectId("id_string") // Important to notice
};
var collection = db.collection('your collection');
collection.find(query, function(err, docs) {
console.log(err, docs);
});
});
Suggestion
//Include ObjectId
var ObjectId = require('mongodb').ObjectID;
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
//Add object id to query object
db.collection('quotes').findOneAndDelete({'_id': ObjectId(uid)}, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});
Yes. thank you i figured where i did wrong. see below correct answer.
var ObjectId = require('mongodb').ObjectID;
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
db.collection('quotes').findOneAndDelete({'_id': ObjectId(uid) }, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});
This response means, your query is executing properly "OK":1, but the find query is unable to find any doc to delete it.
So before using "findOneAndDelete" use only "findOne" and log the response to check weather you that doc or not.