【问题标题】:Mongoose Model containing arrays包含数组的 Mongoose 模型
【发布时间】:2019-02-12 13:40:01
【问题描述】:

首先,我对 MongoDB、Mongoose 和 Express 还是很陌生。我正在尝试创建一个 Mongoose 模型,它有两个数组,我想用多个名为 itemSchema 的对象填充这些数组,但我不确定我应该如何在不使用 findOneAndUpdate 的情况下更新数组,但因为我的数组最初是空的在创建文档之前没有初始 ID。使用我在下面定义的方法 - 食物数组中的任何现有数据都将替换为新数组。下面是我的模型 -

const mongoose = require("mongoose");

const itemSchema = new mongoose.Schema({
  id: String,
  drinks: [
    {
      id: String,
      name: {
        type: String,
        required: true
      },
      price: {
        type: String,
        required: true
      },
      description: {
        type: String
      },
      date: {
        type: Date,
        default: Date.now
      }
    }
  ],
  food: [
    {
      name: {
        type: String,
        required: true
      },
      price: {
        type: String,
        required: true
      },
      description: {
        type: String
      },
      date: {
        type: Date,
        default: Date.now
      }
    }
  ]
});

module.exports = Item = mongoose.model("item", itemSchema);

我不知道我是否正确定义了架构。我知道它不是很干燥(因为两个数组都包含相同的类型),但是因为我相信这是一个如此简单的用例,所以当我可以创建一个模式时,我不想为饮料和食物定义两个单独的模式.

router.post("/food", async (req, res) => {
  try {
    // Create an object from the request that includes the name, price and description
    const newItem = {
      name: req.body.name,
      price: req.body.price,
      description: req.body.description
    };
    // pass the object to the Items model
    let item = new Items(newItem);
    // add to the comments array
    console.log("the new comment ", newItem);
    item.food.unshift(newItem);
    item.save();
    // return the new item array to confirm adding the new item is working.
    res.json(item);
  } catch (error) {
    // Display an error if there is one.
    res.send(404).json(error);
  }
});

上述方法的问题来自我应该如何更新数组。例如,我定义了下面的函数来更新食物数组,但每次都会创建一个新数组。我相信这与没有我可以用来为模型提供 findOneAndUpdate 方法的 Id 参数有关。任何帮助将不胜感激。提前谢谢你。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    根据我的意见,您可以使您的架构更简单,因为您的食物和饮料数组中的所有字段都是相同的,因此您可以简单地多取一个字段作为itemType,然后您不需要取两个单独的子文档用于食物和饮料。

    const mongoose = require("mongoose");
    
    const itemSchema = new mongoose.Schema({
      id: String,
      itemType: { type: String },   //  FOOD or DRINK 
      name: {
         type: String,
         required: true
      },
      price: {
          type: String,
          required: true
      },
      description: {
          type: String
      },
      date: {
          type: Date,
          default: Date.now
      }
    });  
    

    如果您想了解更多关于使用findOneAndUpdate() 更新数组的信息,那么我将解释使用此函数执行的两个简单任务。

    CASE:1 如果您的子文档数组为空,那么您可以在您的子文档中推送新文档,如下所示:

        var updatedData = await Model.findOneAndUpdate(
                {
                    _id: doc._id           
                },
                { 
                    $push: {
                        drinks: {
                            name: drink.name,
                            price: drink.price,
                            description: drink.description,
                        }
                    },
                },{ new: true }
        ).lean().exec();
    

    CASE:2 如果您想通过子文档 id 更新现有的子文档,则可以如下更新:

    var updatedData = await Model.findOneAndUpdate(
                {
                    'drink._id': drinkId           
                },
                { 
                    $set: {                  
                        'drink.$.name': drink.name,
                        'drink.$.price': drink.price,
                        'drink.$.description': drink.description,
                    },
                },{ new: true }
        ).lean().exec();
    

    【讨论】:

    • 谢谢,我认为添加 item_type 字段是我想要完成的目标的方法。
    猜你喜欢
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 2020-04-22
    • 2013-05-14
    • 2016-12-30
    • 2017-09-26
    • 2013-02-09
    • 1970-01-01
    相关资源
    最近更新 更多