i have an application that's supposed to do CRUD, very simple. i want to update a book's info but it doesn't work so what should i change ? plus i'm getting this error now :
core.js:6210 ERROR TypeError: Cannot read properties of undefined (reading 'value')
backend code :
//EDIT ONE BOOK BY NAME
booksRoute.route('/edit/:name').put((req,res,next)=>{
BookModel.findOneAndUpdate(req.params.name,
{$set:false},
(error,data)=>{
if (error){
console.log(error);
return next(error);
}else{
res.json(data) ;
console.log('data updated successfully');
}
})
})
FRONTEND CODE :
<div id="bg"><div >
<ul>
<form #f="ngForm" (ngSubmit)="onSubmit(f)" ngNativeValidate>
<li>
<label>book's name *</label>
<input name="name" type="text" required>
</li>
<li>
<label>book's genre *</label>
<input name="genre" type="text" ngModel required>
</li>
<li>
<label>book's author *</label>
<input name="author" type="text" ngModel required>
</li>
<li>
<label>rating *</label>
<input name="rating" type="number" [max]="10" min="0" ngModel required>
</li>
<li>
<label>price *</label>
<input name="price" type="number" ngModel required>
<input type="submit"/>
</li>
</form>
</ul>
</div>
</div>
service
//edit one book by it's name
editBook(name:string, data){
return this.http.put(this.backendUrl '/edit/' name,data) ;
}
edit-component.ts
onSubmit(f){
console.log("name value:" f.name.value)
this.apiService.editBook(f.name.value,f.value).subscribe( res => {console.log('backend\' response:',res)}) ;
}
CodePudding user response:
so the problem is you are not specifying a field to update do something like this:
booksRoute.route('/edit/:name').put((req,res,next)=>{
BookModel.findOneAndUpdate({ name: req.params.name },
{$set: {
fieldname: false
}},
(error,data)=>{
if (error){
console.log(error);
return next(error);
}else{
res.json(data) ;
console.log('data updated successfully');
}
})
})
Edit: I have updated the code indeed there was a mistake I was not passing the filter correctory I have changed that so now it should work.
also, if you want to learn more visit this site
CodePudding user response:
finally i found the solution after reading documentations. i have two obvious mistakes in my code, the first one is that i didn't assign my input field that i'm gonna use to filter the update request to [(ngModel)] ('name'). so it's like this in my template:
<li>
<label>book's name *</label>
<input name="name" type="text" [(ngModel)]="f.name" required>
</li>
the next mistake is that findOneAndUpdate method is missing the request body so it should be like this to work :
//EDIT ONE BOOK BY NAME
booksRoute.route('/edit/:name').put((req,res,next)=>{
BookModel.findOneAndUpdate(req.params.name,req.body,
{new:true},
(error,data)=>{
if (error){
console.log(error);
return next(error);
}else{
console.log(data)
res.json(data) ;
console.log('data updated successfully');
}
})
})