mongodb - 在猫鼬中更改数组的顺序不会保存
问题描述
我正在使用拖放库来更改元素的顺序,并且我需要保存该顺序,以下方法确实更改了文档但不会保存它,我尝试了 doc.save() 和这个更新方法,记录的文档的顺序已更改,但未在数据库中更新。
module.exports.changeListOrder = async(req, res) => {
const { id, listID, oldIndex, newIndex } = req.body;
await Board.findById(id).then(async(doc) => {
let tmpdoc = doc.lists[oldIndex];
doc.lists[oldIndex] = doc.lists[newIndex];
doc.lists[newIndex] = tmpdoc;
await Board.updateOne({ _id: id }, { $set: { list: doc.lists } })
});
}
我的模型有
lists: [{ header: String, listItems: Array }]
解决方案
您正在混淆 Promise 和异步语法。异步语法是这样的:
module.exports.changeListOrder = async (req, res) => {
const { id, listID, oldIndex, newIndex } = req.body;
const thisBoard = await Board.findById(id);
// this code won't run until thisBoard has returned a value
let [oldValue, newValue] = [thisBoard.lists[oldIndex], thisBoard.lists[newIndex];
thisBoard[oldIndex] = newValue;
thisBoard[newIndex] = oldValue;
let saveOperation = await Board.save(thisBoard);
// console.log(saveOperation);
// return saveOperation or do something with res()
};
推荐阅读
- css - 使用 nth-child 将 css 动画持续时间添加到不同的元素
- java - 如何使用retrofi根据id获取详细信息
- pip - 安装使用的命名空间包的依赖项
- email - Outlook 中电子邮件的简短预览显示图像 src 而不是替代文本
- microsoft-graph-api - https://graph.microsoft.com/v1.0/places/microsoft.graph.room Api 未提供更新数据
- ionic-framework - ion-back-button 无法与 canDeactivate 防护一起正常工作
- django - Django在ajax请求后重定向
- javascript - 表单验证后如何进行表单操作?
- java - 为什么在 java 中 5.24% 1 = 0.2400000000000002?
- javascript - 将对象打印为字符串