Chanter08
Chanter08

Reputation: 151

mongoose - Delete element by id

I am trying to delete a specific property by passing the id of the property, however, the delete removes the first property in the database and not the specific one.

Server.js

app.delete('/deleteProperty/:id', function(req,res) {
  Property.findOneAndRemove(req.params.propertyId,req.body, function(err,data) {
      if(!err) {
        console.log("Deleted");
      }
  });
});

api.service.ts

deleteProperty(id:number) {
        return this.http.delete('http://localhost:3000/deleteProperty/'+id)
        .do(data => console.log('All: ' + JSON.stringify(data)))
        .catch(this.handleError);
    }

propertyDetail.component.ts

deleteProperty(id)
    {
        this.apiService.deleteProperty(id)
        .subscribe( res => {
           //        this._router.navigate(['/properties']);
        }, (err) => {
            console.log(err);
        }
        )
    }

Button in html

<a style="float:right"  color="warn" mat-raised-button (click)="deleteProperty(property.propertyId)">Delete</a>

Upvotes: 2

Views: 18267

Answers (1)

Ivan Vasiljevic
Ivan Vasiljevic

Reputation: 5718

When you are using findOneAndRemove you need to wrap first parameter like this:

Property.findOneAndRemove({_id: req.params.propertyId}, req.body, function(err,data)
{
    if(!err){
        console.log("Deleted");
    }
});

If you try method findByIdAndRemove then you can call it like you did:

Property.findByIdAndRemove(req.params.propertyId,req.body, function(err,data)
{
    if(!err){
        console.log("Deleted");
    }
});

More information you can find in documentation.

Upvotes: 7

Related Questions