如何使用Mongoose将json导入MongoDB

dhj*_*dhj 11 json mongoose mongodb node.js

我有一些问题,这是什么让它变得棘手,所以......

我正在使用Mongoose和MongoLab,我可以存储数据并检索它很好,但我想要一个允许我做数据库基础种子的系统.

我有为集合创建的模式,但没有运行因为没有数据,所以我似乎无法运行正常的mongoimport,因为尚未创建集合.

我想在我的节点服务器上添加一些东西,这样如果集合不存在或为空,它会为集合加载一个模式,然后为种子数据插入json.

所以我有这个......

var Club = require('./schemas/Club');
Run Code Online (Sandbox Code Playgroud)

我通常使用Club.find或Club.save等工作正常.

我想对一个需要创建的Club集合运行一个对象数组的保存.

我确实研究了mongoose-fixture但是它没有多年更新,并且可能有一种方法可以做到这一点而不需要那么多额外的代码,因为我已经定义了模式,并且json数组已经准备就绪.

这是我列出的成功事件,当我想要进行检查和导入时.

mongoose.connection.on('open', function () {
  console.log('mongoose.connection.opened');
});
Run Code Online (Sandbox Code Playgroud)

另外,要考虑,如果我想创建两个集合,并且当它为第一个集合中的项生成ObjectId()时,我可以想象想要将第二个集合中的那些用作ref.

假设Club对象现在只有一个字符串属性.

// contents of data/club.json
[
  { 'name' : 'Barcelona' },
  { 'name' : 'Real Madrid' },
  { 'name' : 'Valencia' }
]
Run Code Online (Sandbox Code Playgroud)

任何帮助非常感谢

Syl*_*oux 17

如果我理解得很清楚,您只需要将一个JSON文档从Mongoose上传到MongoDB集合.鉴于您的模型已命名Club,您可以通过访问原始驱动程序方法Club.collection.并insertMany用来实现你想要的.

这是一个独立的例子(有趣的东西在最后):

> 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();
... })
Run Code Online (Sandbox Code Playgroud)

并查看Mongo Shell:

> db.clubs.find()
{ "_id" : ObjectId("5574b464b680174d79e37601"), "name" : "Barcelona" }
{ "_id" : ObjectId("5574b464b680174d79e37602"), "name" : "Real Madrid" }
{ "_id" : ObjectId("5574b464b680174d79e37603"), "name" : "Valencia" }
Run Code Online (Sandbox Code Playgroud)