【发布时间】:2015-11-16 00:49:32
【问题描述】:
我正在解析一个 JSON 文件,它是一个对象数组。我正在尝试用一些逻辑解析这个数组,然后通过 mongoose 将每个条目保存到 mongodb。
var fs = require('fs');
var Promise = require("bluebird");
var Show = require('../server/models/show');
Promise.promisifyAll(fs);
// read file
fs.readFileAsync('upcoming-shows.json', 'utf8')
.then(function (resolve, reject) {
var shows = JSON.parse(resolve);
shows.forEach(function(show){
// first entries have no date
if(typeof show.date != 'undefined'){
var formatDate = show.date.split('\n')[1].trim(); // Thu 08 Oct 2015
show.date = formatDate;
var newShow = new Show(show);
newShow.headline = show.headline;
newShow.eventLink = show.eventLink;
newShow.eventImage = show.eventImage;
newShow.venue = show.venue;
newShow.dateString = show.date;
// console.log(newShow);
newShow.save(function(err, s){
console.log(s);
});
}
});
});
newShow 对象看起来像一个 mongodb 对象
{ dateString: 'Fri 25 Sep 2015',
headline: 'Gui Boratto',
eventLink: 'http://www.songkick.com/concerts/24627124-gui-boratto-at-mighty',
eventImage: 'http://images.sk-static.com/images/media/profile_images/artists/404729/large_avatar',
date: Fri Sep 25 2015 00:00:00 GMT-0700 (PDT),
venue: 'Mighty',
_id: 55d7c0e461ed8df612ad232b,
artists: [] }
我的猫鼬模型看起来像:
var mongoose = require('mongoose');
// show model schema
var showSchema = mongoose.Schema({
artists: [{ type : mongoose.Schema.ObjectId, ref : 'Artist' }],
venueId: { type : mongoose.Schema.ObjectId, ref : 'Venue' },
date: { type: Date },
ticketUrl: { type: String },
headline: { type: String },
eventLink: { type: String },
eventImage: { type: String },
venue: { type: String },
dateString: { type: String }
});
module.exports = mongoose.model('Show', showSchema);
但是该条目没有保存到 mongodb!为什么没有将数据添加到数据库中?
【问题讨论】:
-
我建议你仔细检查你的模型,甚至可以在这里发布。如果在调用 save 之前正确输出对象,则问题不在此代码中。
-
@Nocturno 是的,我认为你是对的,问题可能发生在他的 model.js 中
-
在保存回调函数中,您忽略了
err变量。我建议检查一下是否返回了错误。
标签: json node.js mongodb mongoose