繁体   English   中英

MongoDB 对象数组更新

[英]MongoDB array of objects update

我正在尝试更新 mongoose 中的用户信息对象数组。 我已经在登录过程中存储了用户核心信息,我想在用户尝试下订单时更新一些用户信息。 这是 model 的代码

const mongoose = require('mongoose');
const { ObjectId } = mongoose.Schema;

const userSchema = new mongoose.Schema(
  {
    name: String,
    email: {
      type: String,
      required: true,
      index: true,
    },
    role: {
      type: String,
      default: 'subscriber',
    },

    info: [
      { country: String },
      { city: String },
      { address: String },
      { phone: String },
      { birthdate: Date },
      { gender: { type: String, enum: ['Male', 'Female'] } },
    ],
    //   wishlist: [{ type: ObjectId, ref: "Product" }],
  },
  { timestamps: true }
);

module.exports = mongoose.model('User', userSchema);

在我的 controller 中,我从前端反应应用程序以 JSON 格式获取数据,我想将一些数据推送到 info 这是用户 Z20F35E630DAF44DBFA4C3F68F5399D 中的对象数组。

exports.createOrder = async (req, res) => {
  // Here I constract the data
  const { plan, service, fullName, country, city, address } = req.body.order;
  const { user_id } = req.body;

  // This the method I tried
  try {
    const user = await User.updateOne(
      {
        _id: user_id,
      },
      {
        $set: {
          'info.$.country': country,
          'info.$.city': city,
          'info.$.address': address,
        },
      },
      { new: true }
    );
    if (user) {
      console.log('USER UPDATED', user);
      res.json(user);
    } else {
      res.json((err) => {
        console.log(err);
      });
    }
    const newOrder = await new Order({
      orderPlan: plan,
      orderService: service,
      orderUser: user_id,
    }).save();
    console.log(newOrder);
    console.log(req.body);
  } catch (error) {
    console.log(error);
  }
};

我厌倦了其他解决方案,例如

 const user = await User.updateOne(
      {
        _id: user_id,

        info: { $elemMatch: { country, city, address } },
      },
      { new: true }
    );

那么我需要重新格式化我的 model 还是有办法更新这个对象数组?

选项1

使用$[]

db.collection.update(
  {},
  { $set: { "info.$[i].country": "a1" }} ,
  { arrayFilters: [ { "i.country": "a" } ] }
)

演示 - https://mongoplayground.net/p/UMxdpyiKpa9


选项 2

  • 如果你知道索引

演示 - https://mongoplayground.net/p/41S7qs6cYPT

db.collection.update({},
{
  $set: {
    "info.0.country": "a1",
    "info.1.city": "b1",
    "info.2.address": "c1",
    "info.3.phone": "d1"
  }
})

建议 -

  • 将信息架构更改为 object 而不是数组

暂无
暂无

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

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