简体   繁体   English

使用nodejs在mongodb中删除对象导致错误

[英]deleting object in mongodb using nodejs causing error

Hello am trying to delete object in my mongodb using nodejs. 您好,我正在尝试使用nodejs删除mongodb中的对象。 Here is my code : 这是我的代码:

module.exports.deletetopic = function (req, res) {
//var id = JSON.parse(req.body)._id;
var idd = req.query.id;
console.log('iddd dans serveur ' + idd);
Topic.findById(idd, function(err, topic) {
  if (err) throw err;


//console.log(topic.title);

  topic.delete(function(err) {
    if (err) throw err;

    console.log('Topic successfully deleted!');
  });

});
}

But i get the following error : topic.delete is not a function 但我收到以下错误: topic.delete is not a function

And here is how i call it on my client side : 这就是我在客户端上如何称呼它:

$scope.deletetopic = function (id) {
  console.log('id est de ' + id);
  $http.delete('/api/deletetopic', {params:{id:id}});
  }

Can you help 你能帮我吗

You should use db.collection.remove() to remove documents from a collection in MongoDb. 您应该使用db.collection.remove()从MongoDb中的集合中删除文档。

topic.remove(function(err) {
   if (err) throw err;
   console.log('Topic successfully deleted!');
});

Also as suggested you should follow these practices as well. 另外,还建议您也遵循这些做法。

Topic.findById({id: idd}, function(err, topic) {
...
...
if(topic){
   // your query
}
else{
   console.log('some message');
}

You can remove document by using ModelName.remove({_id:receivedId}) 您可以使用ModelName.remove({_id:receivedId})删除文档

Topic.remove({_id:idd}).exec(function (err,doc) {
  if (err) {
    return res.status(400).send('Error while deleting');
  }
  if(doc.result.n != 0){
    return res.status(200).send('Deleted');
  }
  return res.status(400).send('Not found');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM