javascript - 用户保存未保存且没有错误

标签 javascript node.js mongodb mongoose passport.js

我有以下用于更新待办事项的代码:

router.post('/edit/todo', function(req, res) {
  var post = req.body,
  newTitle = post.title,
  newDetails = post.details.replace(/\n/g, '<br>'),
  // _id = post._id;
  index = post.index;

  console.log('req.user.todos[index] = ' + JSON.stringify(req.user.todos[index])); // old details

  req.user.todos[index].title = newTitle;
  req.user.todos[index].details = newDetails;

  req.user.save(function(err) {
    if (err) return console.log(err);
    else {
      console.log('req.user.todos[index] = ' + JSON.stringify(req.user.todos[index]));    // new details
      res.redirect('/');
    }
  });
});

router.get('/', function(req, res) {
  var todos = req.user.todos; // old details
}

这是用户架构:

var UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },

    email: {
        type: String,
        unique: true,
        required: true 
    },

    password: {
        type: String,
        required: true
    },

    // keeps the tasks like homework and projects
    // each todo is made of a title, and details
    todos: [],

    // keeps the test
    // each test is made of a subject and a date
    // each date is made up of a month and a day
    tests: [],

    // keeps the schedule 
    // used by tomorrow tile
    schedule: { },

    // links for school related sites
    // each link is made up of a name and an href
    links: []
});

这真的很奇怪,因为在保存阶段它没有错误,并显示了新的详细信息,但看起来它实际上并没有保存用户。
另外,我有几乎相同的方法来创建待办事项(只是使用 push 而不是输入值)并且效果很好。

最佳答案

由于您没有定义 schema 中 todo 数组包含的内容,因此您需要通过调用 markModified 来告诉 Mongoose 何时修改了其元素中的数据。 :

req.user.todos[index].title = newTitle;
req.user.todos[index].details = newDetails;
req.user.markModified('todos');

关于javascript - 用户保存未保存且没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26814801/

相关文章:

javascript - npm --version 给出 errormodule.js :538 throw err; ^ Error: Cannot find module

javascript - 管理流的生成器和迭代器的正确模式是什么

mongodb - 为什么我的 mongodb 索引这么大

mysql - 使用 (No)SQL 的 Rails 微博

javascript - svg 动画动画不流畅

javascript - 选择id中有双点的元素,报错: "#octo:cat" is not a valid selector

javascript - 过滤和删除数组中的过滤元素

javascript - 当使用 ajax 方式进行登录状态检查时,Internet Explorer 会强制显示 304

javascript - Node : Cannot read property 'length' of undefined

python - 如何访问 Pandas DataFrame 中嵌入的 json 对象?