How to update node node with node.js? - node.js

I cannot update the node in the database with neo4j.the update process does not occur. If the problem is not the question of the code, I could not figure out the writing of the code.
app.post('/Movie/update',function(req, res){
var title = req.body.title;
var title = req.body.title2;
session
.run('MATCH (n:Movie {title:{titleParam}}) SET n.title={titleParam} RETURN n',{titleParam:title, title2Param:title})
.then(function(result){
res.redirect('/');
session.close();
})
.catch(function(err){
console.log(err);
});
res.redirect('/');
});
HTML code:
<form method="POST" action="/movie/update">
<br>
<input type="text" name="title">
<input type="text" name="title2">
<br>
<input type="submit" value="Submit">
</form>

In addition to #jfriesenhahn's answer, your Javascript code is also assigning 2 different values to the same title variable. You should use 2 different variables:
var title = req.body.title;
var title2 = req.body.title2;
session
.run('MATCH (n:Movie {title: $title}}) SET n.title= $title2 RETURN n',
{title: title, title2: title2})
or, more simply:
session
.run('MATCH (n:Movie {title: $title}}) SET n.title= $title2 RETURN n',
{title: req.body.title, title2: req.body.title2})
This answer also uses the now-preferred $foo syntax for parameters (instead of the deprecated {foo} syntax).

So, it may just be a typo on your part, but you are using titleParam twice.
I think they cypher you are looking for is:
MATCH (n:Movie {title:{titleParam}}) SET n.title={title2Param} RETURN n

Related

MeanStack: conflict on editing feature'_id' would modify the immutable field '_id'

I've seen solutions in this post and in others, but I did follow the instructions and I'm still getting the error. I understand all the logic, id's can't be replaced, they are immutable, but in my mean stack app, the error persists. The code:
Node route
router.put("/:id" ,(req, res, next) => {
const note = new Note({
_id:req.body.id,
project: req.body.project,
note: req.body.note,
date:req.body.date,
});
Note.updateOne({ _id: req.params.id }, note).then(result => {
console.log(result)
res.status(200).json({ message: "Update successful!" });
});
});
Front End edit component:
ngOnInit(): void {
this.notesForm=this.fb.group({
note:['', Validators.required],
project:['', Validators.required],
date:[null,Validators.required]
})
this.route.paramMap.subscribe((paraMap:ParamMap)=>{
if(paraMap.has('noteId')){
this.mode='edit';
this.noteId= paraMap.get('noteId');
this.note=this.notePadService.getNote(this.noteId)
.subscribe(noteData=>{
this.note = {id: noteData._id, note: noteData.note, date: noteData.date, project: noteData.project};
})
}else{
this.mode='create';
this.noteId=null;
}
})
this.getProjects();
}
onSubmit(){
if(this.mode==='create'){
this.notePadService.submitNotes(this.notesForm.value)
console.log(this.notesForm.value);
this.router.navigate(['/notes-listing'])
}else{
this.notePadService.updateNote(
this.noteId,this.notesForm.value
)
}
}
Service:
getNote(id:string){
return this.http.get<any>('http://localhost:3000/api/notes/'+id)
}
updateNote(id:string,note:Notes){
this.http.put('http://localhost:3000/api/notes/'+id,note)
.subscribe(response=>console.log(response))
}
Also I cant pre-populate the reactive form with the values to edit:
<label>Select a Project</label>
<select (change)="test($event.target.value)" formControlName="project"
class="form-control">
<option
*ngFor="let p of projects"
[value]="p.name">{{ p.name }}</option>
</select>
<!------->
<label for="notes">Note</label>
<textarea class="form-control" formControlName="note" type="text" rows="4"></textarea>
<div class="input-group">
<mat-form-field appearance="fill">
<mat-label>Choose a date</mat-label>
<input formControlName="date" matInput [matDatepicker]="picker">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</div>
<button mat-raised-button color="warn">Submit</button>
</form>
When I click the edit button (in another component), I get the correct URL but no values, and onsubmit, the backend crashes:
http://localhost:4200/edit/601ec21882fa6af20b454a8d
Can someone help me out? I'm very confused and I cant understand the error since I've done everything the other posts suggest...
when you call updateOne you already pass as the first argument the id that should be updated. As second argument you pass note that should contain only the properties that will be updated, but not _id itself:
const note = {
project: req.body.project,
note: req.body.note,
date:req.body.date,
};

Cannot read property toLowerCase of undefined using Adonis and PostgreSQL

I'm using Adonis with PostgreSQL and I am trying to implement a search where a user would be able to search through posts using the title
I have my code structured like so
<form action="{{ route('search') }}" method="GET" style="outline:none">
<input class="shadow appearance-none border-2 p-2 h-10" style="outline:none" type="text" name="q" placeholder="Search the forum" value="{{ request.input('q', '') }}">
</form>
and my controller like so
'use strict'
const Post = use('App/Models/Post')
const Database = use('Database')
class SearchController {
async index ({ view, request, response, params }) {
let posts = await Post.query()
.forIndex()
.whereRaw('lower(title) LIKE ?', params.searchString.toLowerCase())
.paginate(request.input('page', 1), 10)
return view.render('index', {
posts
})
}
}
module.exports = SearchController
However, I am getting the following error:
Instead of name='q' try name='searchString' in the form
See https://adonisjs.com/docs/4.1/request#_methods to get query string parameters in adonis

Passing data from one page to another using Node, Express & EJS

I've got the following routes set up:
router.get('/', function(req, res) {
res.render('index', {});
});
router.post('/application', function(req, res) {
res.render('application', {twitchLink : req.query.twitchLink});
});
I've got the two views set up properly.
This is what I've got in the 'index' view:
<form class="form-horizontal" action="/application", method="post", role="form">
<input type="url" name="twitchLink" required>
<button class="btn btn-success">Submit</button>
</form>
Submitting this form does take me to the application view.
<script>var twitchLink = <%- JSON.stringify(twitchLink) %></script>
<script>console.log(twitchLink)</script>
This should log out the link that I submitted, right?
However, I get these two lines:
Uncaught SyntaxError: Unexpected end of input
Uncaught ReferenceError: twitchLink is not defined
I think you need to put quotes around <%- JSON.stringify(twitchLink) %>, like this:
var twitchLink = '<%- JSON.stringify(twitchLink) %>'
In your example, it will come out as:
var twitchLink = foo.bar.com
What you want is:
var twitchLink = 'foo.bar.com'

Rendering data in handlebars using express framework

Hello I am working in Express Framework, I am using handlebars to render the data from my mysql table. While trying to render the data using below code,instead of rendering value it displaying [object object]. I posted my code below.
index.js:
var query = connection.query('SELECT * FROM requestor_auth WHERE question_id = ? AND answer = ? AND app_key = ? LIMIT 1', [data.qid, data.ansvalue, data.appid], function(err,rows)
{
if(err) {
console.log("Error Selecting : %s ",err );
res.redirect('/');
} else {
res.render('requestform',{page_title:"Edit Customers - Node.js",data:rows});
}
requestform.hbs:
<div class="addressto">
<h4>To,</h4>
<br>
<span style="font-size:18px;margin-left:10px;">The Collector Of</span>
<input type="text" value="{{data}}" class="line" class="text-line" style="margin-left:35px;"><br>
</div>
The value in the form input displaying as [object object]. I tried as data.key_value to render the data but it is not displaying the value.
Please give me a solution. Thank you.
Because the result of Mysql response is array so it should be:
var query = connection.query('SELECT * FROM requestor_auth WHERE question_id = ? AND answer = ? AND app_key = ? LIMIT 1', [data.qid, data.ansvalue, data.appid], function(err,rows) {
if(err) {
console.log("Error Selecting : %s ",err );
res.redirect('/');
} else {
res.render('requestform',{page_title:"Edit Customers - Node.js",data:rows[0]});
}
If there's a same error you should console.log() your result to check the value.
The rows argument in your callback function is by a select query always an array of objects. With handlebars you should be able to do the following:
<div class="addressto">
<h4>To,</h4>
<br>
<span style="font-size:18px;margin-left:10px;">The Collector Of</span>
<input type="text" value="{{data[0].answer}}" class="line text-line" style="margin-left:35px;">
<br>
</div>
Also multiple class names can be in one class attribute.

How to catch the object_id of a post submit in Node.js (MongoJS)?

I have this code in app.js where I insert the content of the title and content fields to their respective document fields in MongoDB:
//post to 'post/new'..
app.post('/post/new', function(req, res){
//get the `title` and `content` fields & save them as variables to be later reused (they rely on the `name:` values).
var title = req.body.title;
var content = req.body.content;
//call the database and find the `_id` to be used in the redirect later..
db.local.find({_id: ObjectId(req.params.id)}, function(id) {});
//insert the title and content in the database (taken from the submit form)
db.local.insert ( {title: title, content: content},
//not sure if I really need to define an err&doc right now so to be ignored..
function(err, doc) {
//redirect to "localhost.com/post/(post)_id/(post)title"
res.redirect('/post/'+req.params.id+'/'+req.body.title);
});
});
This is what I have on post_new.ejs:
<form method="post">
<div>
<div>
<span>Title :</span>
<input type="text" name="title" id="editPostTitle" />
</div>
<div>
<span>Content :</span>
<textarea name="content" rows="20" id="editPostBody"></textarea>
</div>
<div id='editPostSubmit'>
<input type="submit" value="Send" />
</div>
</div>
</form>
The problem is that I get all but no _id in the res.redirect to work, meaning, the title works wonderfully, but the _id no..
How can I get the object id to work in the redirect? Thank you!
EDIT
This is the problem I get and think it's unrelated..but I'll include it for the full view of the issue.
500 Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
Assuming you are using the native node MongoDB driver the callback of the insert function returns the array of inserted objects.
The example in those docs is a pretty good one. Adjusted for your example, it would like something like this:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
db.collection('local').insert({title: title, content: content}, function(err, docs) {
console.log('Inserted _id is '+docs[0]._id);
});
});
Regarding your error, it sounds like req.params.id is not a valid BSON ObjectId.

Resources