Node.js 节点mongoose更新数组中的对象不';行不通

Node.js 节点mongoose更新数组中的对象不';行不通,node.js,mongoose,Node.js,Mongoose,我正在尝试更新一组对象,但没有成功。。 update语句不起作用 我可能需要更新表实例数组并使用新值更新它,然后保存表 const picked = table.meta.permissions.find(obj => obj._id == req.params.permissionId); console.log('picked: %j', picked); // need to update it ! //如何使用req.body中的新值更新此权限对象 table.sav

我正在尝试更新一组对象,但没有成功。。 update语句不起作用

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

  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););
我在“元”字段中有一个权限数组: 型号

    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用新值更新表实例权限

控制器

    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

update语句无法正确运行的原因


感谢您的反馈

我找到了解决此问题的方法,但我不知道这是否是最好的方法? 我使用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); );
    }

您应该查明到底是什么导致了500个错误(通过检查日志文件和/或显式记录错误)。。。我怎样才能在某处获得Mongoose输出日志。。。在我的index.js文件中,我添加了:mongoose.set('debug',(collectionName,method,query,doc)=>{debug(
${collectionName}.${method}
,util.inspect(query,false,20),doc);});但我不知道打印出来的地方…你应该添加到Express中。我不确定你的代码中有什么
debug
。非常感谢你让我走上正轨。。。在我的错误处理程序中,我忘记将环境更改为“测试…”。。。我现在正在获取堆栈跟踪。。。在问题窗口中查看我的更新堆栈跟踪看起来像一条红鲱鱼:它由于某种奇怪的原因在摩卡内部破裂,但这不是500错误的原因。