I did a restful delete to remove a record by id.. It didn't return me any error, but the record isn't get removed in my collection
my route
app.delete('/api/genres/:id',function(req,res){
var id = req.params._id;
var genre = req.body;
Genres.deleteGenre(id, function(err,genre){
if(err){
throw err;
}
res.json(genre)
})
});
my model (I'm using mongoose)
//Delete Genre
module.exports.deleteGenre = function (id, callback) {
var query = {_id: id};
Genre.remove(query, callback);
}
it even return ok status with
{"ok":1,"n":0}
app.delete('/api/genres/:id',function(req,res){
var id = req.params.id;
Genres.deleteGenre(id, function(err,genre){
if(err){
throw err;
}
res.json(genre)
})
});
//Delete Genre
module.exports.deleteGenre = function (id, callback) {
var query = {_id: id};
//use this to findByIdAndRemove in mongoose, it will work
Genre.findByIdAndRemove(query, callback);
}
you don't need to take anything in var genre = req.body
Try this!!!
Happy Coding!!!
use findById to get the document first then you will be able to remove them
Genre.findById(req.params.id, function(err, genre){
if(err) { return res.send(500, err); }
genre.remove(function(err){
if(err) { return res.send(500, err); }
return res.send(204);
});
});
Related
I wanna insert record in textarea with formart
name1|url2
name2|url2
name3|url3
My schemas collections
name:String,
url:String,
please help me, thanks everyone
You can use:-
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/test';
var data1={
name:'name1',
url:'url1'
};
var data2={
name:'name2',
url:'url2'
};
var data3={
name:'name3',
url:'url3'
};
MongoClient.connect(url, function(err, db) {
if(err!=null){
return console.log(err.message)
}
//insertOne
db.collection("App").insertOne(data1,function (err,data) {
if(err!=null){
return console.log(err);
}
console.log(data.ops[0]);
});
//insertMany
var Data=[data1,data2,data3];
db.collection("App").insertMany(Data,forceServerObjectId=true,function (err,data) {
if(err!=null){
return console.log(err);
}
console.log(data.ops);
});
db.close();
});
Hi everyone I am new to mysql and would like to test if the same genre exist in a database and if it does it returns a status code and if the genre does not exist the genre is added into the database. I am currently having the following issues, it is able to check if the genre exist and return the status code but when entering a different genre it reacts the same way as if the genre exist :
file 1
Insertgenre:function(genre,description,callback){
var dbConn=db.getConnection();
// connects to the mysql database (contains an asyn function that returns a callback)
dbConn.connect(function(err){
if(err){
console.log(err);
return callback(err,result);
}else{
// Query for get all rows from genre table where genre = entered genre
var checkSql = 'SELECT genre FROM genre WHERE genre = ?';
dbConn.query(checkSql, [genre], function(err1, result) {
if(err) {
return callback(err,result);
}else {
// Checking if the result length is more than 0.
if(result.length > 0) {
return callback(err1,result);
}else {
var sql="insert into genre(genre,description) values(?,?)";
dbConn.query(sql,[genre,description],function(err,result){
dbConn.end();
if(err) {
console.log(err);
}
return callback(err,result);
}
}
}
});
file 2
app.post('/genre', function(req,res){
var genre = req.body.genre;
var description = req.body.description;
genreDB.Insertgenre(genre,description,function(err,err1,result){
if(err){
//console.log(err)
res.type('json');
res.statusCode=500;
res.send(`{"Result":"Internal Error"}`);
}if(err1){
console.log(err1)
res.type('json');
res.statusCode=422;
res.send(`{"Result":"The genre name provided already exists"}`);
}
else{
res.type("json");
res.statusCode=204;
//res.send(result);
console.log(result);
res.send(`{"Affected Rows":"${result.affectedRows}"}`);
}
});
});
Your callback function expects err to be a normal database error, and err1 to indicate that the genre already exists.
You need to call callback() with 3 arguments to match what it expects.
You also have a typo. In the second query, the callback function's argument is err1, but you used if(err).
And in file 2, you should use else if(err1) since all these conditions are mutually exclusive.
Insertgenre: function(genre, description, callback) {
var dbConn = db.getConnection();
// connects to the mysql database (contains an asyn function that returns a callback)
dbConn.connect(function(err) {
if (err) {
console.log(err);
return callback(err, false, result);
} else {
// Query for get all rows from genre table where genre = entered genre
var checkSql = 'SELECT genre FROM genre WHERE genre = ?';
dbConn.query(checkSql, [genre], function(err1, result) {
if (err1) {
return callback(err1, false, result);
} else {
// Checking if the result length is more than 0.
if (result.length > 0) {
return callback(null, true, result);
} else {
var sql = "insert into genre(genre,description) values(?,?)";
dbConn.query(sql, [genre, description], function(err, result) {
dbConn.end();
if (err) {
console.log(err);
}
return callback(err, false, result);
}
}
}
});
});
})
I have the following code in NodeJS which works well to;
Begin a MySQL transaction;
Create an audiopost;
Update an audiopost.
Check to see if tag1 exists and if not, create it and insert into a tag table. If it does exist simply insert it to the tag table.
Commit the transaction;
But now I'd like to also check for tag2 and tag3 also.
Unfortunately, I can't figure out where and how to place the commit block
in order to keep it all as a single transaction.
If I put it just before the closing of the check for "tag1" the code won't get as far as "tag2" and "tag3". But if I put it after then the closing brackets to the connection queries are in the wrong place. Here's the code;
var mysql = require("mysql");
var express = require("express");
var connection = require("../database");
var createAudiopost = function(req, res, next){
var title = req.body.title;
var userid = req.body.userid;
var opid = req.body.opid;
var tag1 = req.body.tag1;
var tag2 = req.body.tag2;
var tag3 = req.body.tag3;
connection.beginTransaction(function(err) {
if (err) { throw err; }
connection.query('INSERT INTO ?? (title,userid,opid) VALUES (?, ?, ? )', ['audioposts',title,userid,opid], function(err, result) {
if (err) {
connection.rollback(function() {
throw err;
});
}
var audioname = userid + '-' + result.insertId + '.m4a';
var newid = result.insertId;
console.log("newid: " , newid );
connection.query('UPDATE ?? SET audioname=? WHERE audioid = ?', ['audioposts',audioname,newid], function (error, result, fields) {
if (err) {
connection.rollback(function() {
throw err;
});
}
if (tag1) {
connection.query('SELECT tagid FROM tags WHERE tagname = ?', [tag1], function (error, result, fields) {
if (err) {
connection.rollback(function() {
throw err;
});
}
const tagid1 = result[0].tagid;
if (result < 1) {
connection.query('INSERT INTO tags SET tagname = ?', [tag1], function (error, result, fields) {
if (err) {
connection.rollback(function() {
throw err;
});
}
console.log("lets see this ridiculous result", result);
const tagInsertId = result.insertId;
connection.query("INSERT INTO entitytag SET audioid = ?, tagid = ?, userid = ?", [newid, tagInsertId, userid], function (error, result, fields) {
if (err) {
connection.rollback(function() {
throw err;
});
}
connection.commit(function(err) {
if (err) {
connection.rollback(function() {
throw err;
});
}
console.log('success!');
newid = result.insertId;
res.json({
"title" : title,
"userid" : userid,
"opid" : opid,
"insertid": newid
}); //resjson success
}); //commit
}); // insert entitytags
}); // insert tags
} // if row
else {
connection.query("INSERT INTO entitytag SET audioid = ?, tagid = ?, userid = ?", [newid, tagid1, userid], function (error, result, fields) {
if (err) {
connection.rollback(function() {
throw err;
}); //err
} //err
connection.commit(function(err) {
if (err) {
connection.rollback(function() {
throw err;
});
}
console.log('success!');
res.json({
"title" : title,
"userid" : userid,
"opid" : opid,
"insertid": newid,
"tag1": tag1
}); //resjson success
}); //commit
}) // insert entitytag2
}
}); //select tagid
}//tag1
}); //update
}); //insert
}); //begin transaction
} //createaudiopost
module.exports = createAudiopost;
Any suggestions for how I can complete such a complex transaction? I basically need to repeat the entire section of if (tag1) for tag2 and tag3.
I am building a user sign up and crud app. I have a db model.
var valid;
module.exports = {
connectDB: function(){
}
,
findUser: function(req,res) {
}
,
createUser: function(email,name,password){
var role = 'view';
var sql = "INSERT INTO `users`(email, name, password, role) VALUES (" + "'"+email+"'"+","+"'"+name+"'"+","+"'"+password+"'"+","+"'"+role+"'"+")";
db.query(sql, function(err, result){
if(err){
console.log(`FAILED: ${err}`)
return false; // tried setting valid to false
}
else
{
console.log(`User Created`);
valid = true;
}
});
return valid; // this also returns undefined
}
}
I want to be able to return a bool depending up on the succession of the query. I tried returning true/false. I did some searching on why this happens. Firstly there was an explanation about js being asynchronous.
My question is what is the correct way of returning values in function when exporting so that I can use it?
By using promises
createUser: function(email,name,password){
return new Promise(function(resolve,reject){
var role = 'view';
var sql = "INSERT INTO `users`(name, password, role) VALUES (" + "'"+email+"'"+","+"'"+name+"'"+","+"'"+password+"'"+","+"'"+role+"'"+")";
db.query(sql, function(err, result){
if(err){
console.log(`FAILED: ${err}`)
reject(err);
}
else
{
console.log(`User Created`);
resolve();
}
});
})
}
we can now use createUser like so;
db.createUser(email,name,password).then(function(){
console.log('redirect');
res.redirect('/');
}).catch(function(){
console.log('something went wrong');
res.render('signup', { message: 'something went wrong' })
});
Small problem when using POST and adding an INSERT. Works as below, but want to use a callball after the data has been inserted. At the moment the database is being updated. (good) but can't use the callback - I would expect this to be just below the throw error. So you could use result.insertId. Any thoughts welcome?
router.post('/group/:id', function(req, res) {
var idToken = req.params.id;
admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
var userID = decodedToken.uid;
var name = encrypt(req.body.group);
getID(userID, function(result){
var ID = result;
var post = {ID:ID, name:name};
db.query('INSERT INTO cu_groups SET ?', post, function (error, results, fields) {
if (error)throw error;
//*** when I add response here get 502 bad gateway error.
});
res.sendStatus(200);
}); // depends on getID
// admin.auth cat
}).catch(function(error) {
res.sendStatus(error);
});
});
try this way :
router.post('/group/:id', function(req, res) {
var idToken = req.params.id;
admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
var userID = decodedToken.uid;
var name = encrypt(req.body.group);
getID(userID, function(result){
var ID = result;
var post = {ID:ID, name:name};
db.query('INSERT INTO cu_groups SET ?', post, function (error, results, fields) {
if(error){
return res.status(500).send(error);
}
if(!error && results){
return res.status(200).send(results);
}
});
});
}).catch(function(error) {
return res.status(500).send(error);
});
});
if you want to use callback then ,create a separate function like :
var insertData = function(query,data,callback){
db.query(query, data, function (error, results, fields) {
if(error){callback(error,null);}
if(!error && results){callback(null,results);}
});
});
and call this way inside getID :
getID(userID, function(result){
var ID = result;
var post = {ID:ID, name:name};
insertData('INSERT INTO cu_groups SET ?', post, function (error,data){
if(error){
return res.status(500).send(error);
}
if(data){
return res.status(200).send(data);
}
});
});
Working code below many thanks to Saurabh Mistry. I removed the SET post and added the table fields and values explicity.
router.post('/group/:id', function(req, res) {
var idToken = req.params.id;
admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
var userID = decodedToken.uid;
var name = encrypt(req.body.group);
getID(userID, function(result){
var ID = result;
// query
let query = "INSERT INTO cu_groups (ID, name) VALUES('" + ID + "','" + name + "')";
// execute query
db.query(query, (error, result) => {
if(error){
return res.status(500).send(error);
}
if(!error && result ){
return res.send(result);
}
});
}); // depends on getID
// admin.auth cat
}).catch(function(error) {
return res.status(500).send(error);
});
});