How to import json into MongoDB using Mongoose
If I understand it well, all you need is to upload a JSON document to your MongoDB collection from Mongoose. Given that your model is named Club
, you can access raw driver methods through Club.collection
. And use insertMany
to achieve what you want.
Here is a stand alone example (the interesting stuff is at the end):
> var mongoose = require('mongoose')> var assert = require('assert')> mongoose.connect('mongodb://localhost/test');> var Schema = mongoose.Schema> var clubSchema = new Schema({... name: String,... })> var Club = mongoose.model('Club', clubSchema)// Now, the interesting part:> data = [... { 'name' : 'Barcelona' },... { 'name' : 'Real Madrid' },... { 'name' : 'Valencia' }... ]> Club.collection.insertMany(data, function(err,r) {... assert.equal(null, err);... assert.equal(3, r.insertedCount);... ... db.close();... })
And check from the Mongo Shell:
> db.clubs.find(){ "_id" : ObjectId("5574b464b680174d79e37601"), "name" : "Barcelona" }{ "_id" : ObjectId("5574b464b680174d79e37602"), "name" : "Real Madrid" }{ "_id" : ObjectId("5574b464b680174d79e37603"), "name" : "Valencia" }
Sometimes shell scripts may help:
for filename in *; do mongoimport -d mydb -c $filename --jsonArray done
See also: MongoDB Bulk import using mongoimport from Windows folder