Mongoose save() 不保存更改 [英] Mongoose save() not saving changes

查看:63
本文介绍了Mongoose save() 不保存更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能齐全的 CRUD 应用程序,我正在为其构建一些附加功能.新功能允许用户更改供应商列表.他们可以添加、更新和删除新供应商.添加和删​​除似乎工作得很好,但更新似乎不起作用,即使它遵循我在应用程序其他地方的现有 CRUD 功能中使用的类似方法.这是我的代码:

I have a fully functioning CRUD app that I'm building some additional functionality for. The new functionality allows users to make changes to a list of vendors. They can add new vendors, update them and delete them. The add and delete seem to be working just fine, but updating doesn't seem to be working even though it follows a similar method I use in the existing CRUD functionality elsewhere in the app. Here's my code:

// async function from AXIOS request
const { original, updatedVendor } = req.body;
let list = await Vendor.findOne({ id: 1 });

if (!list) return res.status(500).json({ msg: 'Vendors not found' });

let indexOfUpdate = list.vendors.findIndex(
  (element) => element.id === original.id
);

list.vendors[indexOfUpdate].id = updatedVendor.id;
list.vendors[indexOfUpdate].name = updatedVendor.name;

const updated = await list.save();
res.json(updated);

save() 不会更新数据库端的现有文档.我已经控制台记录了 list.vendors 对象数组确实被更改了,但是 save() 没有进行保存.

The save() isn't updating the existing document on the DB side. I've console logged that the list.vendors array of objects is, indeed, being changed, but save() isn't doing the saving.

关于使用保存方式的说明,这种格式也不起作用:

A note on the manner of using save, this format doesn't work either:

list.save().then(res.json(list));

编辑 2:为了回答有关查看日志的问题,我无法发布完整的 console.log(list.vendors),因为它包含私人信息,但是,我可以确认对列表所做的更改正在显示当我在 VendorSchema 中运行以下命令时:

EDIT 2: To answer the questions about seeing the logs, I cannot post the full console.log(list.vendors) as it contains private information, however, I can confirm that the change made to the list is showing up when I run the following in the VendorSchema:

VendorSchema.post('save', function () {
  console.log(util.inspect(this, { maxArrayLength: null }));
});

然而,保存仍然没有改变数据库端.

However, the save still isn't changing the DB side.

推荐答案

由于您使用的是嵌套对象,Mongoose 将无法检测到所做的更改.您需要在 save

Since you are using nested objects, Mongoose will not be able to detect the changes made. You need to mark the modified as an object before the save

list.markModified('vendors');

这篇关于Mongoose save() 不保存更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆