how to delete object array from node js - node.js

I am creating a simple todolist using react js and node js without database (to store data in objact array) I need to delete elements one by one by clicking. For each element I have Delete button. now todo list delete from front end(react), how to delete it from node any one please help me
todo.js
function Remove(id) {
const updateTodos=[...tasks].filter((obj)=>obj.id!==id)
setTasks(updateTodos)
}
if(isLogged){
return (
<div >
<h1>ToDo List</h1>
<form onSubmit={HandleSubmit}>
<input type="text" placeholder=" Add item..." name="list" value={toDos} onChange={(e)=>setToDos(e.target.value)}/>
<button id="btn" type="submit">Add</button>
</form>
<ul>
{tasks.map(obj=><li key={obj.id}>{obj.toDo}<button type='delete' onClick={(e)=>Remove(obj.id)} >Delete</button>
<input type="checkbox" id="" name=""onChange={(e)=>{
console.log(e.target.checked)
console.log(obj)
setTasks(tasks.filter(obj2=>{
if(obj2.id===obj.id){
obj2.status=e.target.checked
}
return obj2
}))
}} value={obj.status} /> </li>)}
</ul>
<h4>Completed tasks</h4>
{tasks.map((obj)=>{
if(obj.status){
return(<h5>{obj.toDos}</h5>)
}
return null
})}
</div>
);
}
}
export default Todo;
node- index.js
const lists =[
{id: new Date(),toDo:"learn react"}
]
app.post('/Todo',function(req, res){
lists.push({"id":new Date(),"toDo":req.body.list,"status":false})
console.log(lists)
res.status(200).json(lists[lists.length-1])
})
app.get('/Todo', (request, response) => response.status(200).json(lists));

req.body.list.pop()
res.status(200).json({"id":new Date(),"toDo":req.body.list,"status":false})
This will remove the last element in the list

Related

how to get single value from input name field instead of array in NodeJS

I am trying to delete elements from the note list. when I try to match a single name to a list title, it shows an array of items.
i want to match
const input name ===day
and output should be "home" from input name field
but it show ["home","home","home","home"]
here is my delete form code:
<form action="/delete" method="POST">
<% for (let i=0; i<newListItems.length; i++) { %>
<div class="item">
<input type="checkbox" onChange="this.form.submit()" name="checkboxname" value="<%=newListItems[i]._id%>">
<p><%= newListItems[i].name %></p>
</div>
<input type="hidden" name="listName" value="<%= listTitle %>"></input>
<% } %>
</form>
app.js code:
app.post("/delete", function (req, res) {
const deleteItem = req.body.checkboxname
const listName = req.body.listName
console.log(listName)
if (listName === day) {
console.log("hello")
} else {
console.log("custome list value")
}
})
There is 4 hidden inputs rendered with same name listName.
So your request payload will be fulfilled with array of values from all of these inputs.
Move hidden input outside of PHP loop.
The point is to make one input with name='listName' instead of four

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,
};

I can't upload file in adonis js, move is not function

I have the following file type field
<form action = "javascript:;" enctype="multipart/form-data" id="formulario" class="form-horizontal">
<div class="form-group">
<div class="span7">
<input type="file" multiple class="file file-loading" data-preview-file-type="any" id="fileUp" name="fileUp[]">
</div>
</div>
</form>
and in the controller i have this for upload file
const Helpers = use('Helpers')
const myFile = request.file('fileUp')
const directory = Helpers.publicPath()
await myFile.move(directory, {
overwrite: true
})
but return error "move is not function"
i don't understand
Your input is for multiple files (fileUp[]), the docs has a section for multiple file upload,you should use moveAll() instead of move()
await profilePics.moveAll(Helpers.tmpPath('uploads'))
if (!profilePics.movedAll()) {
return profilePics.errors()
}

i have insert all data in input every time i want update some value

i new using Angular and nodejs with mongodb
my problem its i have to insert all data again every time i want update my data
the value appers correctly in my form but if not insert again the all data the input the data not change its update null
my code
my editcliente.html
<input type="text" class="form-control" style="width:34px;height:34px" value="{{id}}" readonly>
<div class="form-group">
<label for="Name"> Name of Customor</label>
<input type="text" class="form-control" formControlName="Name" value="{{name}}">
</div>
<div class="form-group">
<label for="Address"> Address</label>
<input type="text" class="form-control" formControlName="Address" value="{{address}}">
</div>
my cliente.ts
registerUser(id:any){
let name = this.registerForm.value.Name;
let address= this.registerForm.value.Address;
let telephone = this.registerForm.value.Telephone;
let postalcode = this.registerForm.value.PostalCode;
let email = this.registerForm.value.email;
this.myfirstService.getupdate(id,name,address,telephone,postalcode,email).subscribe(data=>{
if(data.success){
console.log("deu")
}
else{
console.log(" nao deu")
}
})
}
app.post('/api/updateCliente',async (req,res)=>{
const {id,name,address,telephone,postalcode,email}= req.body
console.log(id,name,address,telephone,postalcode,email);
const resp = await Clientes.findOne({_id:id})
if(!resp){
res.json({
sucess:false,
message:'invalid cliente'
});
return
}
else{
await Clientes.updateOne({_id:id},{$set:{
name:name,
address:address,
email:email,
telephone:telephone,
postalcode:postalcode}})
res.json({
sucess:true
});
}
})
how i fix this problem
updateOne works on a retrieved document, i.e. your resp that was returned by Clientes.findOne.
Try something like:
resp.updateOne({
name:name,
address:address,
email:email,
telephone:telephone,
postalcode:postalcode})

Reactjs error, objects are not valid as react child?

I'm using reactjs in front end and nodejs as backend. I'm calling my backend (localhost:3001/api/tunes) through this code :
componentDidMount(){
fetch("/api/itunes")
.then((results)=>{
this.setState({queryResult:results});
})
}
This code is supposed to return a single string value which I'm assigning to local state variable queryResult. I can't understand why the code gives error - objects are not valid react child.
My render function :
render(){
return(
<div>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search"
value={this.state.queryValue} onChange={this.handleQueryChange} />
<button class="btn btn-outline-success my-2 my-sm-0" type="submit"
onClick={this.submitQuery}></button>
</form>
<div>{this.state.queryResult}</div>
</div>
);
}
this is what I'm getting from my server:
router.get('/api/itunes',(req,res,next)=>{
request('https://itunes.apple.com/search?term=jack+johnson',
function (error, response, body) {
if (!error && response.statusCode == 200) {
// console.log(body) // Print the google web page.
var result =JSON.parse(body);
res.send(result.results[0].artistName);
}
});
});
You are trying to render whole object which is this.state.queryResult .
React cannot render objects.You must convert this to String or have to extract each value from the object.
You can easily check this using {console.log(this.state.queryResult)}

Resources