【问题标题】:How to structure POST to MongoDB collection with references to ObjectId's of another collection?如何使用对另一个集合的 ObjectId 的引用来构造 POST 到 MongoDB 集合?
【发布时间】:2021-12-31 00:56:36
【问题描述】:

我对 MEAN 项目非常陌生,我的大部分代码都是来自各种教程的代码,这些代码根据我对 MEAN 的有限知识适应了我自己的需求。很抱歉有任何滥用术语的情况,我会尽力解释我的情况。

我有一个 MongoDB 数据库,其中包含两个集合:itemscartsitems 的文档包含每个 item 的产品、颜色、尺寸和价格字段。 carts 的文档具有一个字段,该字段是 items 的数组,引用每个 item 的 ObjectId,一个字段用于 Total,一个布尔字段称为 Active。

我正在努力处理对 cart API 的 POST 请求,其中包括对多个 items 的 ObjectId 的引用。

item.model.js:

module.exports = mongoose => {
  const Item = mongoose.model(
    'item',
    mongoose.Schema({
      product: {
        type: String,
        required: true
      },
      color: {
        type: String,
        required: true
      },
      size: {
        type: String,
        required: true
      },
      price: {
        type: Number,
        required: true
      }
    })
  );

  return Item;
};

cart.model.js:

module.exports = mongoose => {
  const Cart = mongoose.model(
    'cart',
    mongoose.Schema({
      items: [{
        item: {
          type: mongoose.Schema.Types.ObjectID,
          ref: 'Item'
        }
      }],
      total: {
        type: Number,
        required: true
      },
      active: {
        type: Boolean,
        required: true
      }
    })
  );

  return Cart;
};

cart.controller.js 购物车创建:

const db = require('../models');
const Cart = db.carts;


// Create and Save a new Cart
exports.create = (req, res) => {
  // Validate request
  if (!req.body.items) {
    res.status(400).send({ message: 'Content can not be empty!' });
    return;
  }

  // Create a Cart
  const cart = new Cart({
    items: req.body.items,
    total: req.body.total,
    active: req.body.active ? req.body.active : true
  });

  // Save Cart in the database
  cart
    .save(cart)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || 'Some error occurred while creating the Cart.'
      });
    });
};

对 /api/cart/ 的 POST 请求

【问题讨论】:

    标签: node.js arrays mongodb post mean-stack


    【解决方案1】:

    我想通了哈哈。

    像这样格式化 POST 请求成功地将项目添加到 items 字段数组:

    {
        "items": [
            {"item": "616f3f378302f3944caa8fac"},
            {"item": "6182ff5cd852c5a4c7315048"},
            {"item": "6182ff6ad852c5a4c731504c"}
        ],
        "total": 0,
        "active": true
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-10
      • 2021-08-25
      • 2016-08-19
      • 2023-01-10
      • 2023-03-26
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      相关资源
      最近更新 更多