2017-07-26 81 views
0

我有CouponProduct這個模式。我試圖得到的是,當使用API​​添加產品時,將創建特定優惠券的某個unit並將其插入到優惠券中,並且這些優惠券的引用也應該插入到產品中。我正在使用coupon-code包來生成優惠券。使用NodeJS將隨機生成的折扣優惠券保存到Mongodb中

let couponSchema = new Schema({ 
    code: {type: String, unique: true}, 
    status: {type:Boolean, default: false} 
}); 

module.exports = mongoose.model('Coupon', couponSchema); 

let productSchema = new Schema({ 
    prductname: {type: String}, 
    unit: {type: Number}, 
    coupon: [{type: Schema.Types.ObjectId, ref: Coupon}], 
    category: {type: String} 
}); 

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

這是我添加產品的後期API。我能夠將代碼保存到優惠券集合中,但對如何將最近添加的優惠券參考信息保存到產品感到困惑。

api.post('/add', (req, res, next) => { 
    let newProduct = new Product(); 

    newProduct.productname = req.body.productname; 
    newProduct.unit = req.body.unit; 
    newProduct.category = req.body.category; 

    var i; 
    for(i=0; i<=req.body.unit; i++){ 
    var code = ucg.generate(); // ucg is imported from coupon-code package 
    let newCoupon = new Coupon(); 
    newCoupon.code = code; 
    newCoupon.save(err => { 
     if (err) { 
     console.log("error occured"); 
     return; 
     } 
    }); 
    } 

    newProduct.save(err => { 
    if (err) { 
     res.send(err); 
     return; 
    } 
    res.json({message: "Product added successfully."}); 
    }); 
}); 

任何人都可以幫助我找到一種方法來做到這一點?如果我的解釋不夠,請告訴我。

回答

0

我解決它通過添加push方法newProduct.coupon.push(newCoupon.id);

for(i=0; i<=req.body.unit; i++){ 
    var code = ucg.generate(); // ucg is imported from coupon-code package 
    let newCoupon = new Coupon(); 
    newCoupon.code = code; 
    newCoupon.save(err => { 
     if (err) { 
     console.log("error occured"); 
     return; 
     } 
    }); 
    newProduct.coupon.push(newCoupon.id); 
    } 
相關問題