用户保存不保存没有错误

时间:2014-11-08 07:15:09

标签: 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而不是放置值)并且完美无缺。

1 个答案:

答案 0 :(得分:2)

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

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