从GET请求缓存/保存到db a Json Body

时间:2016-06-05 02:24:26

标签: javascript node.js mongodb express mongoose

获得了如何使用node.js和平均堆栈的基础知识后,我想从我自己的项目开始。

问题是:
我无法访问我想保存到mongodb的请求API的json body / attributes,并且每24小时自动更新一次。

我在尝试什么:
是调用2个API。这些响应使用json数据集列表,我试图通过相同的名称合并到我的mongoose Schema中。使用body.param或response.param,没有用。

获取请求的示例响应:
URL1 / API /产品/所有

{
 data: [
  {
  id: 1,
    product_name: "Product1",
    app: appName,
    quantity: 137360,
    price: 0.05,
    updated_at: "2016-06-04 23:02:03",
    median_week: 0.04,
    median_month: 0.05,
  },
  .....
  {
    id:142640
    ...
  }   
}  

url2 / api / item / all?key = apikey

{
  success: true,
  num_items: 6713,
  products: [
            {
             product_name: "Product1",
             ....
             icon_url: "//url/economy/image/bla.png",
             product_color: "8650AC",
             quality_color: "EB4B4B"
             },
             ....

在发现仅表达到本地网址的路线后,我现在正在使用请求 这就是我的路线/ item.js

var express = require('express');
var qs = require('querystring');
var request = require('request');
var _ = require('underscore');
var router = express.Router();
var Item = require('../models/item');



var options = {
    url:  'url2' + ?key + app.config.url2.apikey ,
    port: 80,
    method: 'GET',
    json:true
}

/* GET listing. */
router.get('/', function(req, res) {
  request.get('url', function (error, response, body) {

  if (!error && response.statusCode == 200) {
      console.log(body) // Prints JSON Body
   //Iterate through each id of url1 and num_items of url2 and update collection
   // Better to make another request method just to call the second api?
    for each(item in body.id || body.num_items) {

    var newItem = Item({
      id: item[i],
      product_name: ,

      app: 'appName',
      quantity: res.body.quantity,
      price: res.body.price,
      ....
      icon_url: res.body.,
      name_color: res.body.,
      quality_color: body.,
      created_at: Date.now,
      updated_at:

      })

      newItem.save(function(err) {
        if (err) throw err;

      console.log('Item created');
      })
      //return res.json(body); 
    }
   }
   res.sendStatus('304');
  });

});

这是我的项目模型

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ItemSchema = new Schema({
  id: String,
  ....      
  created_at: {
    type: Date,
    default: Date.now
  },
  updated_at: Date
});


var Item = mongoose.model('Item', ItemSchema);

  ItemSchema.pre('save', function(next) {

   var currentDate = new Date();
   this.updated_at = currentDate;

   if (!this.created_at)
    this.created_at = currentDate;

  next();
});

module.exports = Item;

在写完这个问题后,我认为这不是解决这个问题的最好方法。有没有最好的做法?

1 个答案:

答案 0 :(得分:0)

您有几个问题:

  1. res.body必须是req.body
  2. 您必须异步迭代数组(使用异步包)
  3. 保存所有数据后发送结果
  4. 参见下面的示例

    router.get('/', function(req, res) {
    
        // npm install async --save
        var async = require('async');
        request.get('url', function (error, response, body) {
            if (error && response.statusCode !== 200) {
    
                // request could not be completed
                return res.send(400, {message: 'Something went wrong'});
            } else {
    
                // get the count
                var iterator = body.id || body.num_items;
    
                // iterate number of times
                async.times(iterator, function(number, next){
    
                    // create your new object
                    var newItem = Item({
                        id: number,
                        product_name: ,
                        app: 'appName',
                        quantity: req.body.quantity, // <== not res.body
                        price: req.body.price,
                        icon_url: req.body.,
                        name_color: req.body.,
                        quality_color: body.,
                        created_at: Date.now
                    });
    
                    // save and call next (which is callback)
                    newItem.save(next);
                }, function(timesErr, timesResult){
    
                    // if something failed, return error
                    // even if 1 item failed to save, it will return error
                    if(timesErr) {
                        return res.send(400, {message: 'Something went wrong'});
                    }
                    // send the list of saved items;
                    // or whatever you want
                    res.status(200).send(timesResult);
                });
            }
        });
    });