【问题标题】:!We need to go deeper! Items in mongoDB won't delete!我们需要更深入! mongoDB中的项目不会删除
【发布时间】:2019-11-03 17:33:10
【问题描述】:

我创建了一个简单的 REST 'todo-List',一切正常,除了从我的 mongoDB 中删除项目。

当我通过我的 main.js 文件删除一个项目时,我的“DELETE”方法收到 200 响应。但是该项目并未从 mongoDB 中删除,因此仍显示在我的列表中。

我使用了 deleteOne() 方法而不是 remove(),因为根据我收到的消息,后者已被弃用,但这不会扭转局面。

谁能帮帮忙。

我的 app.js 中的代码访问应该删除项目的数据库。

let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let mongoose = require('mongoose');

mongoose.connect('mongodb+srv://Daniel:xxxxxx@clusterpetertester-h0t6v.mongodb.net/test?retryWrites=true&w=majority', {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true });

let taskSchema = new mongoose.Schema ({
  item: String
})

app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
app.use(express.static('./'))


let Task = mongoose.model("Tasks", taskSchema);

app.get('/todoparents', function(req, res) {
  Task.find({}, function(err, item) {
    if (err) {
    } else {
      res.render('todoparents', {item : item})
    }
  });
});

//submit button route
app.post('/newTask', function(req, res) {
  console.log(' item submitted! ');
  let newItem = new Task({
    item: req.body.input
  })
  Task.create(newItem, function (err, Task) {
    if (err) console.log(err)
    else {
      console.log("Inserted Item : " + newItem)
    }
  })
  res.redirect('todoparents');
});

app.delete('/todoparents/:item', function (req, res) {
  //delete the requested item form mongodb
  Task.find({item: req.params.item.replace(/\-/g,"")}).deleteOne(function (err, data) {
    if (err) throw err;
    res.json(data)
    console.log(data)
  });
});


let port = 3333;
app.listen(port);
console.log('The server is up on port #', port);

这是我的 todoparents.ejs 中的 html

<div class="container">

          <h1>Time to burden the children</h1>

          <ul id="taskList">
              <% for(var i=0; i < item.length; i++) { %>
                <li class="task-item<%=[i] %>"> 
                  <span class="task-info"> <%= item[i].item %> </span>
                  <span class="delete">Delete</span> 
                </li>
             <% } %>
          </ul>     

        </div>

main.js 中的代码在点击我的 todoparents.ejs 时获得正确的“跨度”

//gets the first span in an li and returns the textcontent
let taskList_Ul = document.getElementById('taskList');
taskList_Ul.addEventListener('click', function(e) {

  let clickedElement = e.target;
  let content_clicked_Sibling = clickedElement.previousElementSibling.textContent;

  //the spaces are replaced with not spaces
  let item = content_clicked_Sibling.replace(/ /g, "");

// getting the url and attaching the item which was targeted
  fetch('/todoparents/' + item, {
  method: 'DELETE',
  headers: {
    'Content-Type': 'application/json',
  }
}).then(response => response.json()
    .then(data => {
      return data;
    })
  );
});

这是我从 app.js 中的 console.log(data) 获得的数据。似乎什么都没有被删除,因为最后我们已经 deleteCount: 0

{ n: 0,
  opTime:
   { ts:
      Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1572802291 },
     t: 5 },
  electionId: 7fffffff0000000000000005,
  ok: 1,
  operationTime:
   Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1572802291 },
  '$clusterTime':
   { clusterTime:
      Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1572802291 },
     signature: { hash: [Binary], keyId: [Long] } },
  deletedCount: 0 }

应用的用户体验(非常简单)

尝试删除项目后的控制台图像。

【问题讨论】:

    标签: node.js mongodb express


    【解决方案1】:

    您应该这样做,而不是使用.find()

    Task.deleteOne({item: req.params.item.replace(/\-/g,"")}, function (err, data) {
      if (err) throw err;
      res.json(data)
      console.log(data)
    });
    

    【讨论】:

    • 我尝试使用它,但在这种情况下,我什至没有得到 200 响应。 IE。根本没有状态响应。 :=( 实际上,应用程序崩溃了。
    • 如果它有帮助,我在这里学习了一个教程。 youtube.com/… 但是,这家伙在他的前端 js 中使用了 ajax 请求
    • req.params.item 包含什么?一个数组还是什么?
    • 只是我之前添加的一个项目的字符串。我应该与 main.js 文件中的 span 相同。所以 - 一个项目的字符串将是: {"_id":{"$oid":"5dbee9286474e92080db79cd"}, "item":"eat a meal","__v":{"$numberInt":"0"}}只是MongoDB中的对象中的项这有意义吗?
    • 我可以添加整个 app.js 文件,它可能会有所帮助。请参阅上面的 app.js。之前存在的 app.delete 现在位于该代码的末尾。
    【解决方案2】:

    您使用的主键_id字段的格式是什么?是标准的ObjectId吗?如果是这样,您可能需要在删除之前将作为 _id 字段传递给删除调用的值转换为 ObjectId。否则,您实际上是在发送一个字符串值,该值在 _id 列中找不到,并且 delete 调用删除了零个记录。

    【讨论】:

    • 我不确定,但如果我不删除 ID,是否需要发送主 key_id 的格式?我正在尝试访问数据库中具有我从 html 文档中获得的指定字符串的项目。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多