【问题标题】:User save not saving with no errors用户保存不保存且没有错误
【发布时间】:2015-01-05 01:04:53
【问题描述】:

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

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: []
});

这真的很奇怪,因为在保存阶段它没有错误地通过,并显示了新的详细信息,但它似乎并没有真正保存用户。
此外,我在创建 todos 方面也有几乎相同的东西(只是使用 push 而不是放置值)并且效果很好。

【问题讨论】:

    标签: javascript node.js mongodb mongoose passport.js


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!这两天我一直在努力解决这个问题!
    猜你喜欢
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    相关资源
    最近更新 更多