简体   繁体   English

Mongoose - 如何更新 MongoDB 中数组中的所有对象?

[英]Mongoose - How to update all objects within an array in MongoDB?

I am creating an app where I want to toggle the default address of a person.我正在创建一个应用程序,我想在其中切换一个人的默认地址。
My User Schema contains a field which is an array of delivery addresses which are objects.我的用户架构包含一个字段,它是一个作为对象的交付地址数组。
One of the fields is isDefault , which is the defaultAddress field I want to toggle from true to false and vice versa.其中一个字段是isDefault ,这是我想要从 true 切换到 false 的 defaultAddress 字段,反之亦然。
Specifically, if the user changes their default address, I want to set the rest of the addresses to false and update the one he/she chose to be true具体来说,如果用户更改了他们的默认地址,我想将其余地址设置为 false 并更新他/她选择的地址为 true

User Schema用户架构

const UserSchema = Schema({
 email: {
    type: String,
    required: true,
  },
 deliveryAddresses: [deliverySchema]

Delivery Address Schema送货地址架构

{
      id: {
        type: Schema.Types.ObjectId,
        required: true
      },
      isDefault: {
        type: Boolean,
        required: true,
        default: false,
      },
      name: {
        type: String,
      },
      email: {
        type: String,
      },
      phone: {
        type: String,
      },
     
    }

To do that, what I have done so far is:为此,我到目前为止所做的是:
Getting the email of the user.获取用户的电子邮件。
Getting the id of the delivery address from the user that will be toggled to true.从将切换为 true 的用户那里获取送货地址的 ID。

exports.setDefault = (req, res, next) => {
  const email = req.body.email;
  const id = req.body.id;

  User.findOne({ email: email })
    .then((user) => {
      let addresses = [...user.deliveryAddresses];

      addresses.forEach((address) => {
        address.isDefault = false;
      });
    
      const index = addresses.findIndex((address)=> {
          return address.id.toString() === id.toString();
      });

      addresses[index].isDefault = true;
  
      user.deliveryAddresses = addresses;
      return user.save();  
    })
    .then((doc) => {
      res.status(200).json({
        user: doc,
        statusCode: "200",
        msg: "Address updated successfully",
      });
    })

    .catch((err) => {
      res.status(500).json({
        statusCode: 500,
        error: err,
        msg: "Something went wrong",
      });
    });
};

However, after doing all this, on testing my api on postman, it seems to work, no errors.但是,在完成所有这些之后,在邮递员上测试我的 api 时,它似乎可以工作,没有错误。 But on checking the database, nothing has changed.但是在检查数据库时,没有任何变化。
I am at loss as to what I'm doing wrong.我不知道我做错了什么。

Mongoose is weird.猫鼬很奇怪。 You need to mark the deliveryAddresses sub-object as modified, otherwise its changes won't be saved.您需要将deliveryAddresses子对象标记为已修改,否则将不会保存其更改。

user.markModified('deliveryAddresses');
user.save();

From Mongoose FAQs来自猫鼬常见问题解答

"Mongoose doesn't create getters/setters for array indexes; without them mongoose never gets notified of the change and so doesn't know to persist the new value. There are two workarounds: MongooseArray#set or Document#markModified()." “Mongoose 不会为数组索引创建 getter/setter;没有它们,mongoose 永远不会收到更改通知,因此不知道保留新值。有两种解决方法:MongooseArray#set 或 Document#markModified()。”

Can you try sth like你能试试吗

user.markModified('deliveryAddresses');
user.save();

More on https://mongoosejs.com/docs/faq.html更多关于https://mongoosejs.com/docs/faq.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM