如何读取json文件并将条目保存到mongodb

我parsing的是一个对象数组的JSON文件。 我想用一些逻辑来parsing这个数组,然后通过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: [] } 

我的mongoose模型看起来像:

 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! 为什么不是数据被添加到数据库?

好的,谢谢你的回复。 发生这个问题是因为我试图在一个单独的连接上添加到集合中。 这个答案帮助了我。

在阅读文件之前,我把所有的连接信息都放进去了:

 // database connection stuff var mongoose = require('mongoose'); var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development', envConfig = require('../config/env')[env]; mongoose.connect(envConfig.db); 

然后用节点将文件本身运行一次以添加到数据库