I am new to rethinkdb.
When I try out the sample code in https://github.com/rethinkdb/rethinkdb-example-nodejs/tree/master/todo-angular-express
function create(req, res, next) {
var todo = req.body;
todo.createdAt = r.now(); // Set the field `createdAt` to the current time
r.table('todos').insert(todo, {returnVals: true}).run(req._rdbConn, function(error, result) {
if (error) {
handleError(res, error)
}
else if (result.inserted !== 1) {
handleError(res, new Error("Document was not inserted."))
}
else {
res.send(JSON.stringify(result.new_val));
}
next();
});
}
I got the following error:
500 Internal Server Error
{"error":"return_vals renamed to return_changes in:\nr.table(\"todos\").insert({title: r.json(\"\"abcde\"\"), completed: r.json(\"false\"), createdAt: r.now()}, {returnVals: true})\n
And then I tried out the sample code in http://rethinkdb.com/docs/examples/node-todo/
function create(req, res, next) {
var todo = req.body; // req.body was created by `bodyParser`
todo.createdAt = r.now(); // Set the field `createdAt` to the current time
r.table('todos').insert(todo, {returnChanges: true}).run(req._rdbConn, function(error, result) {
if (error) {
handleError(res, error)
}
else if (result.inserted !== 1) {
handleError(res, new Error("Document was not inserted."))
}
else {
res.send(JSON.stringify(result.changes[0].new_val));
}
next();
});
}
I got the following error:
500 Internal Server Error
{"error":"Unrecognized optional argument returnChanges. in:\nr.table(\"todos\").insert({title: r.json(\"\"abcde\"\"), completed: r.json(\"false\"), createdAt: r.now()}, {returnChanges: true})\n "}
It seems that rethinkdb have changed returnVals to return_changes / returnChanges, and the argument of insert().
And I have the problem fixed when I used return_changes.
What is the right way to work on insert in latest version?
Do rethinkdb always changes its syntax?
this is indeed a bug in the example code. I've opened https://github.com/rethinkdb/rethinkdb-example-nodejs/issues/3 so we can fix it.
Your second problem with returnChanges not being recognized might come from using an old RethinkDB node driver. Have you tried updating the driver? http://rethinkdb.com/docs/install-drivers/javascript/
Related
I have a trouble with mongoDB and Mongoose. I need to store data in mongoDB, because I use it for saving settings. Settings must load when app initializes. The trouble is that database does not always return data. Here are the screenshots to make everything clear:
'Setup' array is returned.
'Setup' array is not returned.
'Setup' array returned 'undefined', so script can't run.
1-3 steps are done randomly!
My question is: how to connect to DB right? Is there any problems with the DB connection? (OS - Linux mint 19)
I tried several ways to connect to this DB:
Setup.find({}).exec()
Setup.findById('...').exec()
etc.
mongoose.connect('mongodb://localhost:27017/config', { useNewUrlParser: true });
const setupSchema = new Schema({
eula: Boolean,
lang: String,
styles: Number
});
mongoose.set('debug', true);
setupSchema.set('collection', 'setup');
const Setup = mongoose.model('Setup', setupSchema);
var eula, lang, styles;
Setup.findById('5ccfaf5a0c3c1612d4e2c905', function(err, setting){
if (err) {
console.log('Setup Init error');
console.log(err);
} else {
console.log('Setup Contents');
if (setting !== null || setting !== undefined){
console.log(setting[0]);
// eula = setting[0].eula;
// lang = setting[0].lang;
// styles = setting[0].styles;
} else {
console.log('Setting is null');
}
}
});
I expect that the data will ALWAYS be returned.
Actual output is shown on screenshots (see above).
UPD: I've now reached this state (on the screenshot below), but still it is not good...
UPD2: I've found the solution! I tried to use MongoDB.Client, not mongoose.
I guess findById function will return an object and not an array.That's why you get this error.
TRY THIS:
Setup.findById('5ccfaf5a0c3c1612d4e2c905', function(err, setting){
if (err) {
console.log('Setup Init error');
console.log(err);
} else {
console.log('Setup Contents');
if (setting){
console.log(setting);
// eula = setting.eula;
// lang = setting.lang;
// styles = setting.styles;
} else {
console.log('Setting is null');
}
}
});
UPDATED CODE:
Setup.findOne({id :'5ccfaf5a0c3c1612d4e2c905'}, function(err, setting){
if (err) {
console.log('Setup Init error');
console.log(err);
} else {
console.log('Setup Contents');
if (setting){
console.log(setting);
// eula = setting.eula;
// lang = setting.lang;
// styles = setting.styles;
} else {
console.log('Setting is null');
}
}
});
I am trying to redirect from the condition of a mysql to a get method but it does not work. How could I solve it?
app.post('/responses/',(req,res)=>{
var {text, context ={} } = req.body;
var params = {
input: {text},
workspace_id: '07',
context
}`
`assistant.message(params,(err,response) => {
if(err){
res.status(500).json(err);
}
else {
res.json(response);
console.log(JSON.stringify(response, null, 2));
}
if(response.context.rfc){
var RFC = response.context.rfc;
connection.connect(function(err) {
if (err) throw err;
connection.query(`SELECT * FROM test where RFC = '${RFC}'`, function (err, result, fields) {
if(result.length){
console.log("login");
}
else {
console.log('no login');
res.redirect('/home'); //Her not redirect.
}
});
});
}
});
});
Because show this error: hrow err; // Rethrow non-MySQL errors ^Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
The error message indicates you are trying to set headers after the response is already sent. From your sample code, looks like your API call (whatever assistant.message is) is returning RFC. You then attempt to redirect to another page, but you've already called res.json, which begins sending a response to the browser.
You need to refactor your controller a bit so that you only call res.redirect or res.json, not both.
I'm using SailsJS as an API with Waterline connected to a MongoDB. I'm trying to put together an endpoint to edit existing DB entries but can't seem to get it to work and I'm hitting a wall as to why.
My route:
'post /edit/safety/:id': {
controller: 'SafetyController',
action: 'editSafety'
},
My controller function:
editSafety: function editSafety(req, res) {
var id = req.params.id;
Safety.findOneById(id).then((err, safety) => {
if (err) {
res.send(500, err);
return;
}
if (!safety) {
res.send(404, err);
return;
}
safety.title = req.body.title;
safety.description = req.body.description;
safety.status = req.body.status;
safety.save((err, updatedSafety) => {
if (err) {
re.send(500, err);
return;
}
res.send(200, updatedSafety);
});
});
},
Any push in the right direction would be greatly appreciated.
I don't recognize the Safety.findOneById method - is this something you have custom built? If not, then it is likely your problem.
Try swapping it for either:
Safety.findOne(id)
or
Safety.findOne({id: id})
Note that the returned object will be a model instance if the record exists, and undefined otherwise. If you decide to go with Safety.find instead then the returned value will be an array containing all models matching the query.
Looks like the main issue was transposing the response and err objects. It was successfully completing the query, but loading it into the err object which gets caught and a 500 error is thrown. So I changed that and simplified in a few other places.
editSafety: function editSafety(req, res) {
var id = req.params.id;
Safety.findOne(id).then((response, err) => {
var safety = response;
if (err) {
res.send(500, err);
return;
}
if (!response) {
res.send(404, err);
return;
}
safety.title = req.body.title;
safety.description = req.body.description;
safety.status = req.body.status;
Safety.update({
id: id
}, safety)
.then((result) => {
res.json(200, 'Ok!');
})
.catch((err) => {
sails.log.error('SafetyController.editSafety', err);
})
});
},
Hello you beautiful people you.
I'm trying to create REST APIs using node.js connected to an OracleDB, but i'm pulling my hair out trying to get these stupid bind variables working.
Here's my code:
app.get('/mailsummary/:SCHEMA', function (req, res) {
"use strict";
oracledb.getConnection(connAttrs, function (err, connection) {
if (err) {
// Error connecting to DB
res.set('Content-Type', 'application/json');
res.status(500).send(JSON.stringify({
status: 500,
message: "Error connecting to DB",
detailed_message: err.message
}));
return;
}
connection.execute("select * from :SCHEMA.event#db3", [req.params.SCHEMA], {
outFormat: oracledb.OBJECT // Return the result as Object
}, function (err, result) {
if (err || result.rows.length < 1) {
res.set('Content-Type', 'application/json');
var status = err ? 500 : 404;
res.status(status).send(JSON.stringify({
status: status,
message: err ? "Error getting vendor mailing summary." : "Vendor or DB does nto exist.",
detailed_message: err ? err.message : ""
}));
} else {
res.contentType('application/json').status(200).send(JSON.stringify(result.rows));
}
// Release the connection
connection.release(
function (err) {
if (err) {
console.error(err.message);
} else {
console.log("GET /mailsummary/" + req.params.SCHEMA + " : Connection released");
}
});
});
});
});
For some reason i'm getting the error
OracleDB : ORA-01036: illegal variable name/number
If I remove the bind variable, assign a static value and remove "req.params.SCHEMA" after the sql statement and leave the brackets blank, it works.
connection.execute("select * from peeps.event#db3", [], {
outFormat: oracledb.OBJECT // Return the result as Object
I know it's got to be something simple with the way i'm pulling in the bind variable, but i'm pulling my hair out.
Please help me Obi-Wan Kenobi... you're my only hope.
Thanks!
Bind variables are placeholders used to transfer data between database and client program. You are trying to transfer the text of the SQL statement - your usage won't work.
This bind behavior is not specific to node-oracledb; it's the way Oracle works. It helps keep data and statement text separate.
There is some general bind info at: http://docs.oracle.com/database/122/LNOCI/binding-and-defining-in-oci.htm#GUID-77A26CEA-1C41-46A2-866C-622F9FEB5482
{ text: undefined,
done: false,
_id: 529e16025f5222dc36000002,
__v: 0 }
PUT /api/todos/529e16025f5222dc36000002 200 142ms - 68b
I keep getting this error when trying to do an update for my simple CRUD todo list. When I submit the update, the change doesn't appear on screen, although the put says it's a 200. Not sure what steps to take so that I don't get this "undefined" error and so I can have the update show up on screen.
EDIT: Included more code
This is the back-end node code:
app.put('/api/todos/:_id', function(req, res) {
Todo.findById(req.params._id, function(err, todos){
todos.text = req.body.text;
console.log(todos);
todos.save(function() {
if (!err) {
res.send(todos);
} else if (err) {
res.send(err);
}
Todo.find(function(err, todos) {
if (err)
res.send(err);
res.json(todos);
});
});
});
});
This is the Angular front-end code:
$scope.updateTodo = function(id) {
$scope.newItem = prompt("Please enter your new item:", "");
$http.put('/api/todos/' + id, {formData: $scope.newItem}).success(function(data) {
$scope.todos = data;
});
$http.get('/api/todos').success(function(data) {
$scope.todos = data;
});
};
I think it's because of this:
$http.put('/api/todos/' + id, { formData: $scope.newItem} )
^^^^^^^^
You're passing a single formData parameter with the request, yet in your Express code, you use this:
req.body.text
Either try this:
req.body.formData.text
Or don't use the formData parameter at all and pass $scope.newItem directly.
Besides that, your Express code is a bit messy: it might send back multiple responses and it doesn't check for errors on the save (as #PaulGray also pointed out).