首页 > 解决方案 > 在猫鼬中更改数组的顺序不会保存

问题描述

我正在使用拖放库来更改元素的顺序,并且我需要保存该顺序,以下方法确实更改了文档但不会保存它,我尝试了 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 }]

标签: mongodbmongoose

解决方案


您正在混淆 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()

};

推荐阅读