【问题标题】:Removing a subdoc using AJAX & Mongoose使用 AJAX 和 Mongoose 删除子文档
【发布时间】:2015-07-07 17:57:09
【问题描述】:

如何在 Mongoose 中使用 AJAX 正确删除子文档(在本例中为任务)?

在加载到页面中的文件中的 ajax 之前,一切似乎都在正常工作。或者问题可能出在控制器上?我读到您不能对子元素执行.remove,我不清楚如何处理删除。

这是架构:

//new user model

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

// Task schema
var taskSchema = mongoose.Schema({
        clientEasyTask             : { type: String },
        clientHardTask         : { type: String },
        clientStupidTask      : { type: String }
});

var userSchema = new mongoose.Schema({
  email: { type: String, unique: true, lowercase: true },
  password: String,

  task             : [taskSchema]
});

module.exports = mongoose.model('Task', taskSchema);
module.exports = mongoose.model('User', userSchema);

页面加载的JS:

// Delete 
$(document).ready(function() {
  console.log('called del function');
  var $alert = $('.alert');
  $alert.hide();
  $alert.on('error', function(event, data){
    $alert.html(data)
    $alert.addClass('alert-danger');
    $alert.show();
  });
  $alert.on('success', function(event, data) {
    $alert.html(data);
    $alert.addClass('alert-info');
    $alert.show();
  })
  $('.task-delete').click(function(event) {
    console.log('click event occurred');
    $target = $(event.target)
    $.ajax({
      type: 'DELETE',
      url: apiDeleteTask + $target.attr('data-task-id'),
      success: function(response) {
        $target.parent.children.id(id).remove();
        $alert.trigger('success', 'Task was removed.');
      },
      error: function(error) {
        $alert.trigger('error', error);
      }
    })
  });
})

Routes,匹配工作更新路由:

var tasks = require('./controllers/tasks-controller'),
var User            = require('./models/user');
var Task            = require('./models/user');
module.exports = function (app, passport) {
// Delete Task
app.delete('/api/tasks/:id', tasks.del);
};

还有 tasks-controller.js

var User = require('../models/user');
var Task = require('../models/user');

exports.del = function(req, res, next) {

  return User.update({ 'task._id': req.params.id }, { $set: { 'task.$.clientEasyTask': req.body.clientEasyTask }},
    (function(err, user) {
        if(!user) {
          res.statusCode = 404;
          return res.send({ error: 'Not phound' });
        }
        if(!err) {
          console.log("Updated Existing Task with ID: " + req.params.id + " to read: " + req.body.clientEasyTask ),
          res.redirect('/dashboard');
        } else {
          res.statusCode = 500;
          console.log('Internal error(%d): %s', res.statusCode, err.message);
          return res.send({ error: 'Server error' });
        }
    })
  );
};

最后但并非最不重要的是,我收到了这个错误,它给出了 task_id 字符串和第 0 行:

[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (54c55ac0443873db1eb8c00c, line 0)

【问题讨论】:

  • 找不到路由,你的服务器需要routes.js吗?
  • 是的,它来自一个正常运行的应用程序。我只是包含了与 ajax 删除功能相关的文件。

标签: ajax node.js mongodb mongoose


【解决方案1】:

为了从子数组(任务)中删除整个字段,解决方案是使用 $unset。我想使用 $set 来更新带有空值的字段,但这正是 $unset 所做的。

这是现在有效的问题行: return User.update({ 'task._id': req.params.id }, { $unset: { 'task.$.clientEasyTask': req.body.clientEasyTask }},

在此处阅读有关字段运算符的更多信息:http://docs.mongodb.org/manual/reference/operator/update-field/

$pull 如果您想删除数组元素而不留下空值,则可以使用,但您必须有一个特定的匹配查询。在此处阅读有关 $pull 和其他数组更新选项的信息: http://docs.mongodb.org/manual/reference/operator/update-array/

另外,如果您遇到问题,我无法强调阅读文档的重要性。我可以向你保证,这里回答问题的每个人都在这样做,或者从这样做的人那里学到了东西。

做这项工作。你会弄清楚的。不要放弃。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 2019-01-04
    • 2019-07-16
    • 2014-05-01
    • 2014-12-02
    • 2020-01-31
    • 2021-02-10
    相关资源
    最近更新 更多