【发布时间】:2016-10-04 21:44:23
【问题描述】:
在了解了如何使用 node.js 和平均堆栈的基础知识之后,我喜欢从我自己的项目开始。
问题是:
我无法访问请求的 API 的 json 正文/属性,我喜欢将其保存到 mongodb 并每 24 小时自动更新一次。
我正在尝试什么:
是调用 2 个 API。这些响应与我尝试以相同名称合并到我的猫鼬模式中的数据集的 json 列表。使用 body.param 或 response.param,没用。
获取请求的示例响应:
url1/api/products/all
{
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"
},
....
在发现只表示到本地 url 的路由后,我现在使用请求。
那是我的路由/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;
写完这个问题后,我认为这不是解决这个问题的最佳方法。有什么最佳做法吗?
【问题讨论】:
-
你有几个问题:
res.body必须是req.body,你必须异步遍历数组(使用async包),保存所有数据后发送结果
标签: javascript node.js mongodb express mongoose