Mongodb 更改mongoose中数组的顺序不会保存

Mongodb 更改mongoose中数组的顺序不会保存,mongodb,mongoose,Mongodb,Mongoose,我正在使用拖放库来更改元素的顺序,我需要保存该顺序,下面的方法确实更改了文档,但无法保存,我尝试了doc.save()和此更新方法,记录的文档的顺序已更改,但在数据库中未更新 module.exports.changeListOrder = async(req, res) => { const { id, listID, oldIndex, newIndex } = req.body; await Board.findById(id).then(async(

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

您混淆了承诺和异步语法。异步语法如下所示:

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()

};

这是工作代码,问题是Mongoose没有为数组索引创建getter/setter;如果没有它们,mongoose永远不会收到更改通知,因此不知道如何保存新值,因此必须使用set()

我编辑了很多错误,但结果是一样的
module.exports.changeListOrder = async(req, res) => {
    const { id, listID, oldIndex, newIndex } = req.body;
    const doc = await Board.findById(id);

    let [oldValue, newValue] = [doc.lists[oldIndex], doc.lists[newIndex]];

    doc.lists.set(oldIndex, newValue);
    doc.lists.set(newIndex, oldValue);

    await doc.save();
};