【发布时间】:2017-05-04 02:02:00
【问题描述】:
我正在尝试更新对象数组,但如果成功.. 更新语句不起作用..
我可能必须更新表实例数组并用新值更新它然后保存表...
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
为什么更新语句没有正确运行
感谢反馈
【问题讨论】:
-
您应该找出导致 500 错误的确切原因(通过检查日志文件和/或显式记录错误)。
-
这是我在测试阶段的问题之一......我怎样才能在某处获得 Mongoose 输出日志......在我的 index.js 文件中,我添加了: mongoose.set('debug', (collectionName , 方法, 查询, doc) => { debug(
${collectionName}.${method}, util.inspect(query, false, 20), doc); });但我不拥有打印输出的位置... -
您应该在 Express 中添加 proper error handling。我不确定您的代码中的
debug是什么。 -
非常感谢您让我走上正确的轨道...在我的错误处理程序中,我忘记将环境更改为“测试...我现在正在获取堆栈跟踪...查看我的在问题窗口中更新
-
该堆栈跟踪看起来像一条红鲱鱼:出于某种奇怪的原因它在 Mocha 内部中断,但这不是 500 错误的原因。