2016-08-11 12 views
2

帆のJS(MongoDBの)中でさらに使用するための変数に結果のデータを格納したい、 はここに私のコードです私は次モデルに格納するデータベースから価格を取得したい

newOrder: function(req,res){ 
    var data = req.body; 
    const orderNo = data.orderNo; 
    const user = data.user; 
    const business = data.business; 
    const inventory = data.inventory; 
    const price = Inventory.find({id: data.inventory}).exec(function(err,record){ return record.price}); 
    const address = data.address; 
    const quantity = data.quantity; 
    const contactNumber = data.contactNumber; 

    Order.create({ 
     orderNo: orderNo, 
     user: user, 
     business: business, 
     inventory: inventory, 
     price: price, 
     address: address, 
     quantity: quantity, 
     contactNumber: contactNumber 
     }).then(function(result){ 
     res.ok(result); 
    }); 
    }, 

Iそれが正しくないことを知っているが、私はそれを行う方法がわからない 内側のクエリは何も返されていない、 私は後で使用するために変数に結果のデータを保存したい。 ここ

答えて

5

を助けてくださいあなたが行く:

newOrder: function(req,res){ 
    var data = req.body; 
    const orderNo = data.orderNo; 
    const user = data.user; 
    const business = data.business; 
    const inventory = data.inventory; 
    const address = data.address; 
    const quantity = data.quantity; 
    const contactNumber = data.contactNumber; 

    Inventory.findOne({id: data.inventory}) 
    .then(function(record) { 
     // Price is available here as record.price, 
     // do whatever you want with it 
     return Order.create({ 
      orderNo: orderNo, 
      user: user, 
      business: business, 
      inventory: inventory, 
      price: record.price, 
      address: address, 
      quantity: quantity, 
      contactNumber: contactNumber 
     }); 
    }) 
    .then(function(createdOrder) { 
     res.ok(createdOrder); 
    }) 
    .catch(function(err) { 
     console.log("Error ar newOrder:", err); 
     return res.serverError(err); 
    }) 
} 

は、基本的には最初のインベントリレコードをフェッチし、次にあなたが Orderクエリでそれを使用することができます。私も Inventory.find.findOne()に交換しました。それはそれがあなたがそれを使いたいと思っていたようです。

関連する問題