0

I am trying to delete the entry from MOngoDb by using MEAN STACK with ANgular 4.(New to this technology)

typescript:

deleteitem(id){
  let deleteresult;
  let itemid = id;
  this.dataService.deleteitem(itemid)
  .subscribe(res =>deleteresult =res,
  err => this.apiError = err,
  )
};

dataservice:

deleteitem(itemid): Observable<any>{
      let data =new URLSearchParams();
      data.set('deleteId', itemid);
      console.log(data.toString());
      return this.http.post(URL, data.toString())
      .map(res=> res.json())
      .catch((error:any) => Observable.throw('Server Error To delete the item'));
       }

Router.js

const ObjectID = require('mongodb').ObjectID; 
 router.post('/deleteitem', function(req, res){
      MongoClient.connect('URL',function(err, client){
      if (err) throw err;
      var myDB = client.db('DbName');
       var collection = myDB.collection('collectionName');
       console.log(req.body);       
       //var objectId = collection.getObjectId();
       collection.remove({_id: ObjectId(req.body.deleteId), function(err, result)
      {
        res.send((result==1)?{msg:deleted} : {msg:"error:"+ err});
      }});
    })
    })

Error:

ObjectId is not defined.

Also the console.log(req.body) gives a "{}" value. Not sure why. But console.log(data.toString()); in the dataservice gives the value of intended _id to be removed from MongoDb.

0

1 Answer 1

1

Try using data instead of data.toString() in

return this.http.post(URL, data.toString())

This will give you output value in console.log(req.body);

Also, try replacing the below line of code

collection.remove({_id: ObjectId(req.body.deleteId), function(err, result)

with

collection.deleteOne({_id: new mongodb.ObjectID(req.body.deleteId)}, function(err, result)

You need to create a new instance of mongodb here. Hope this works.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.