我们如何使用猫鼬创建对集合的引用

时间:2019-11-28 11:09:50

标签: node.js mongodb mongoose

如果这个问题似乎与我之前已经问过的问题有关,请原谅我,我觉得我第一次没有很好地解决这个问题。

我已基于以下数据创建了资源路由,该数据是从我的应用程序播种到Mongodb中的

// seeder.js

"_id": "5d7a514b5d2c12c7449be020",
        "issuedBy": "Ola",
        "collectedBy": "Ola",
        "quantity": "8",
        "product": "5d713995b721c3bb38c1f5d0",

我的问题是这个;如何在订单集合中实际保存产品objectId“ 5d713995b721c3bb38c1f5d0”

exports.getOrders = asyncHandler(async (req, res, next) => {
  if (req.params.productId) {
    const orders = await Orders.find({ product: req.params.productId });

    return res.status(200).json({
      success: true,
      count: orders.length,
      data: orders
    });
  } else {
    res.json(orders);
  }
});

通过上述路线,我设置了一个条件,该条件基于URL中是否存在ProductId,该条件将在Orders集合“ Orders.find({product:req.params.productId})”内进行匹配


//Product Schema
const ProductSchema = new mongoose.Schema({
   name : String,

   description : String,
   price : Number,
   quantity :  Number,
   supplier :String

},{timestamps:true});

module.exports = mongoose.model('Product', ProductSchema)


// Orders Schema


   const OrderSchema = new mongoose.Schema({

   issuedBy : String,
   collectedBy: String,
 quantity: Number,
   product: {
         type: mongoose.Schema.ObjectId,
         ref: 'Product',
         required: true
       },


},{timestamps:true});


const Orders = mongoose.model("Orders", OrderSchema);

// Export model
module.exports = Orders;

我实际上如何创建将productId保存在Orders集合中的路线,例如“ 5d713995b721c3bb38c1f5d0”?

1 个答案:

答案 0 :(得分:1)

我认为一个订单可以有多个产品。因此,我将产品的名称更改为producs,并使其成为数组。

此外,对于模型名称,最好使用单数命名约定。

我将像这样设置模式和模型:

产品型号:

const mongoose = require("mongoose");

const ProductSchema = new mongoose.Schema(
  {
    name: String,
    description: String,
    price: Number,
    quantity: Number,
    supplier: String
  },
  { timestamps: true }
);

module.exports = mongoose.model("Product", ProductSchema);

订单模型:

const mongoose = require("mongoose");

const OrderSchema = new mongoose.Schema(
  {
    issuedBy: String,
    collectedBy: String,
    quantity: Number,
    products: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Product",
        required: true
      }
    ]
  },
  { timestamps: true }
);

module.exports = mongoose.model("Order", OrderSchema);

您可以使用以下代码创建包含产品的订单:

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const url = "mongodb://localhost:27017/ord";
const Order = require("./models/order");
const Product = require("./models/product");

const port = 3000;

app.use(express.json());

mongoose
  .connect(url, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(() => {
    app.listen(port, () => {
      console.log(`App running on port ${port}...`);
    });
  })
  .catch(error => console.log(error));

app.post("/order", async (req, res) => {
  let result = await Order.create(req.body);
  res.send(result);
});

app.get("/order/:orderId", async (req, res) => {
  const result = await Order.findById(req.params.orderId).populate("products");
  res.send(result);
});

您可以使用以下正文创建到http://localhost:3000/order的产品的订单:(您必须使用现有的产品ID)

{
    "issuedBy": "issuedBy",
    "collectedBy": "collectedBy",
    "quantity": 123,
    "products": ["5ddfb388b14c5b41e0607a5e","5ddfb376b14c5b41e0607a5d"]
}

响应:

{
    "products": [
        "5ddfb388b14c5b41e0607a5e",
        "5ddfb376b14c5b41e0607a5d"
    ],
    "_id": "5ddfb418b14c5b41e0607a5f",
    "issuedBy": "issuedBy",
    "collectedBy": "collectedBy",
    "quantity": 123,
    "createdAt": "2019-11-28T11:48:40.500Z",
    "updatedAt": "2019-11-28T11:48:40.500Z",
    "__v": 0
}

要获取此订单及其产品时,您需要向http://localhost:3000/order/5ddfb418b14c5b41e0607a5f发送GET请求,网址中的ID是我们之前创建的订单的ID,因此您需要使用订单ID。

如果您还希望能够将产品添加到现有订单中,则可以添加以下代码:

app.post("/order/:orderId/:productId", async (req, res) => {
  const result = await Order.findByIdAndUpdate(
    req.params.orderId,
    {
      $push: {
        products: req.params.productId
      }
    },
    { new: true }
  );
  res.send(result);
});

因此POST网址必须包含如下所示的orderId和productId: http://localhost:3000/order/5ddfb418b14c5b41e0607a5f/5ddfb67c721b885790ec837b

响应:

{
    "products": [
        "5ddfb388b14c5b41e0607a5e",
        "5ddfb376b14c5b41e0607a5d",
        "5ddfb67c721b885790ec837b"
    ],
    "_id": "5ddfb418b14c5b41e0607a5f",
    "issuedBy": "issuedBy",
    "collectedBy": "collectedBy",
    "quantity": 123,
    "createdAt": "2019-11-28T11:48:40.500Z",
    "updatedAt": "2019-11-28T11:59:51.659Z",
    "__v": 0
}