我正在学习NodeJS并试图在本地建立一个模拟网站。基本上,它是一个使用WOW AuctionHouse API的网站。我从请求中获取数据,将其解析为JSON并尝试将其写入数据库。问题是,如果我把auctions.save放在请求中它不会将.save函数识别为一个函数(假设我超出了它的范围)并且如果我把它置于问题之外来自异步性质我得到我的数据库中的空条目。这是代码:
var express = require('express');
var hbs = require('express-hbs');
var mongoose = require('mongoose');
//var blizzard = require('blizzard.js').initialize({ apikey: "xxx" });
mongoose.connect('mongodb://127.0.0.1/blood_of_sargeras')
var post = mongoose.model(
'post',
{
name: String,
type: String,
price: String
});
var app = express();
app.engine('hbs', hbs.express4({
partialsDir:__dirname+'/views/partials'
}));
app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');
app.use('/static', express.static('static'));
var request = require("request");
var url = "http://auction-api-eu.worldofwarcraft.com/auction-data/xxx-xxx/auctions.json"
var auctions = new post;
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
auctions = JSON.stringify(body);
post.save(function (err) {
if(err)
console.log("Error with database!");
else
console.log("Data written to DB!");
})
}
});
app.get('/', function (req, res){
post.find({}, function (err, o){
if (err)
console.log('Database error!');
else{
res.render('index', o);
}
});
});
app.listen(80, function(){
console.log('Listening on port 80')
});
这甚至是正确的方法吗?有没有更好的办法?我已经坚持了很长一段时间,它变得非常令人沮丧。我尝试的其他事情是:
答案 0 :(得分:1)
我认为您可能需要将您的请求包装在事件监听器中。这将确保在服务器完成启动后而不是之前运行请求。这是一个简单的例子。
app.on('listening', function () {
// Run your request to the WoW auction house once the express server has started up
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
auctions = JSON.stringify(body);
post.save(function (err) {
if(err)
console.log("Error with database!");
else
console.log("Data written to DB!");
})
}
});
});
答案 1 :(得分:0)
试试这个:
var postSchema = mongoose.Schema({name: String,mType: String,price: String});
var post = mongoose.model('Post',postSchema);
var newPost = new Kitten();
然后在请求中:
newPost.name = auctions.name;
newPost.mType = auctions.type; //do not use type it is reserved
newPost.price = auctions.price
newPost.save(function(err, mPost) {
if (err) console.error(err);
console.log(mPost);
});