簡體   English   中英

如何將數據保存到 mongoose 中的數組

[英]how to save data to the array in mongoose

我正在構建一個應用程序,用戶可以在其中保存許多圖像及其名稱。 我希望將該信息存儲在數組中的 mongoose 中。 這個怎么做?

這是我的用餐模式,

const MealSchema = new mongoose.Schema({
  userId: {
    type: String,
    required: true,
  },
  meals: [
    {
      mealImg: {
        type: String,
      },
      mealName: {
        type: String,
      },
    },
  ],
});

如何將數據保存到此架構。

我希望結果是這樣的:

    { _id: 5fd662b596ac96247463fab8,
    userId:"someid"
     meals: [
    {
    _id:23242fff,
        mealName:"meal1",
        mealImg:"https://meal1.png"
        },
_id:23242fff,
    mealName:"meal2",
    mealImg:"https://meal3.png"
    },
_id:23242fff,
    mealName:"meal3",
    mealImg:"https://meal4.png"
    },
    ] }

你可以這樣寫:

Meal.insert({ userId: someId, meals: arrayOfMeals })

但這不是一個好的做法,因為您可以將不必要和不正確的信息放入數組中。 此類問題通過中間表和它們之間的鏈接來解決。 我建議您創建另一個表,其方案如下:

const UsersMealsSchema = new mongoose.Schema({
  userId: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
  mealId: {type: mongoose.Schema.Types.ObjectId, ref: 'Meal'},
});

然后更改您的 Meals shema:

const MealSchema = new mongoose.Schema({
  id: {
    type: string,
    required: true,
  }
  mealImg: {
    type: String,
    required: true,
  },
  mealName: {
    type: String,
    required: true,
  },
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM