如何使用Node JS从响应Crud删除数据到mongoDB

时间:2019-07-16 13:52:59

标签: node.js reactjs mongodb hook

我无法使用reactjs和node js删除mongodb中的值

  • 这是我发送到节点js的react hooks axios post方法
    const deleteUser = id => {
            var data={"id":id}
             axios.post('http://localhost:8010/api/social/deletedata',data)
            .then((res) => {
                console.log('response',res);
            })
            .catch((error) => {
                console.log('error block called',error);
            })
            setEditing(false)
            setUsers(users.filter(user => user.id !== id))
            }

  • 这是我的节点js代码
     router.post('/deletedata', function(req, res, next) {
          console.log("deleted values are",req.body)
        //var id = req.body;

        MongoClient.connect(url, function(err, db) {
          assert.equal(null, err);
          var myId = JSON.parse(req.body.id);
          db.collection('customers').deleteMany({"_id": objectId(myId)}, function(err, result) {
            assert.equal(null, err);
            console.log('Item deleted');
            db.close();
          });
        });
      });

1 个答案:

答案 0 :(得分:0)

我认为您需要将_id作为ObjectID传递,尝试这样

var mongodb = require('mongodb');


 router.post('/deletedata', function(req, res, next) {
          console.log("deleted values are",req.body)
        //var id = req.body;

        MongoClient.connect(url, function(err, db) {
          assert.equal(null, err);
          db.collection('customers').deleteMany({"_id": new mongodb.ObjectID(req.body.id)}, 
          function(err, result) {
            assert.equal(null, err);
            console.log('Item deleted');
            db.close();
          });
        });
      });