簡體   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