将订单与产品相关联

时间:2019-04-12 04:08:17

标签: node.js mongoose

我在尝试将特定订单与特定产品关联时遇到问题。我是node.js的新手,我想添加一个产品(关联并填充订单),然后重定向到显示我创建的产品的所有订单的页面

创建了产品和订单模式(对其他模式不太确定)...

这是我的产品型号

next

这是订单模型:

var mongoose= require("mongoose");
var productSchema = new mongoose.Schema({
    name:String,
    brand:String,
    price: Number, 
    image: String,
    description:String,
    featured: Boolean,

 });

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

例如,我希望使用var mongoose = require("mongoose"); var orderSchema= new mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, products:[ { type: mongoose.Schema.Types.ObjectId, ref:"Product", required:true } ] , quantity :{type:Number, default:1} }); module.exports=mongoose.model("Order",orderSchema); 方法将此模型关联在一起,进行填充,然后出现在路径(“ mongoose)上。例如,我是编程新手,因此最简单的答案将不胜感激。

1 个答案:

答案 0 :(得分:0)

这是一个使用Express.Js的小示例,在此示例中,我创建了3个模型:

D

我的D将嵌入客户订购的产品,我选择将产品存储为subdocuments,因为我的库存很少,您也可以选择存储references。 br /> 注意:我每个客户仅引用一个订单,您可以选择其他方式,然后在// Models const productSchema = new mongoose.Schema({ name:String }); var orderSchema= new mongoose.Schema({ products:[productSchema] }); const clientSchema = new mongoose.Schema({ name: String, order: { type: mongoose.Schema.Types.ObjectId, ref: 'Order' } }) const Product = mongoose.model('Product', productSchema); const Client = mongoose.model('Client', clientSchema); const Order = mongoose.model('Order', orderSchema); 中将订单字段放入数组(orderSchema)中 在我的控制器中,我有2种方法:一种创建订单,另一种向订单添加产品。

clientSchema

我知道需要两种方法:一种是使用所有可用产品绘制表格,另一种是使用已订购商品绘制购物车。

order: [{ /* type...*/}]

我需要两个(由路由处理程序渲染):

// Controller
const createOrder = (userId, productId) => {
  Product.findOne({_id: productId}) // find a product
    .exec()
    .then(product => new Order({products: [product]}).save()) // save the products into the order
    .then(order => Client.findOneAndUpdate({_id: userId}, {$set: {order: order}}).exec())// update the client document with the new order
    .then(client => res.json(client)); // respond with json
    // .catch(err => console.log(err))
}
const addToOrder = (userId, productId) => {
  return Product.findOne({_id: productId}) // find the product
    .exec()
    .then(product => {
      return Client.findOne({_id: userId})//find the client
        .populate({ path: 'order', populate: { path: 'order.products' } })
        .exec() //populate in order to access client.order.products
        .then(client => {
          client.order.products.push(product);
          return client.order.save();
        })
    })
    // .catch(err => console.log(err));
}

我希望这会有所帮助。

相关问题