Reputation: 3314
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.
Upvotes: 0
Views: 442
Reputation: 1436
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.
Upvotes: 1