node mongoose更新数组中的Object并不起作用

时间:2017-05-03 13:23:04

标签: node.js mongoose

我正在尝试更新一个对象数组,如果成功的话...... 更新语句不起作用..

我可能必须更新表实例数组并使用新值更新它,然后保存表...

  const picked = table.meta.permissions.find(obj => obj._id == req.params.permissionId);
  console.log('picked: %j', picked); // need to update it !

//如何使用req.body中的新值更新此权限对象?

  table.save()
    .then(savedTable => res.json(savedTable))
    .catch(e => next(e););

我在' meta'中有一组权限。领域: 的 MODEL

    const Schema = mongoose.Schema;
    const Permission = new Schema({
      permission: {
        role_id: { type: String },
        canWrite: { type: Boolean }
      }
    });
    const TableSchema = new mongoose.Schema({
      meta: {
        name: { type: String, required: true },
        permissions: [Permission],
        ...
      },
      ...
    );

在控制器中,我首先加载请求的表并将其附加到req对象,然后执行updatePermission函数,并尝试使用$ set

使用新值更新表实例权限

CONTROLLER

    import Table from '../../models/table.model';

    /**
     * Load table  and append to req.
     */
    function load(req, res, next, id) {
      Table.get(id)
        .then((table) => {
          req.table = table;
          return next();
        })
        .catch(e => next(e));
    }

    function updatePermission(req, res, next) {
      const table = req.table;

      console.log('Current table.meta.permissions: %j', table.meta.permissions, '\n');
      console.log('update permission: ', req.params.permissionId, ' with: ', req.body, '\n');

      const query = { 'meta.permissions._id': req.params.permissionId }
      const update = { $set: { 'meta.permissions.$.permission': req.body } };
      const options = { new: true};
      table.update(query, update, options)
        .then(savedTable => res.json(savedTable))
        .catch((e) => { next(e); });

}

控制台日志显示当前表权限以及req.params和req.body

为什么更新语句无法正常运行

感谢您的反馈

1 个答案:

答案 0 :(得分:0)

我找到了解决这个问题的方法,但我不知道它是否是最好的一个? 我使用some()更新表对象然后保存表..

    function updatePermission(req, res, next) {
      const table = req.table;

      table.meta.permissions.some((obj, idx) => {
        if (obj._id == req.params.permissionId) {
          table.meta.permissions[idx].permission = req.body; 
          return true;
        }
        return false;
      });

      table.save()
        .then(savedTable => res.json(savedTable))
        .catch(e => next(e); );
    }