我需要使用mongoose从许多json文件导入数据,但我似乎无法找到方法。 现在我只是使用mongoDB命令导入文件:
mongoimport --db dbName --collection collectionName --file fileName.json --jsonArray
有没有办法用猫鼬做到这一点?使用猫鼬是否是正确的方法(我使用expressJs)?如果不是使用json文件中的数据填充数据库的正确方法?
这是我迄今为止在server.js
中所做的
/ Set up
var express = require('express');
var app = express(); // create our app w/ express
var mongoose = require('mongoose'); // mongoose for mongodb
var ObjectId = require('mongodb').ObjectID; // objectID
var morgan = require('morgan'); // log requests to the console (express4)
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var cors = require('cors');
// Configuration
mongoose.connect('mongodb://localhost/data');
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({ 'extended': 'true' })); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// Models
var Review = mongoose.model('Review', {
title: String,
description: String,
rating: Number
});
var Site = mongoose.model('Site', {
title: String,
description: String,
rating: Number
});
// Routes
// Get reviews
app.get('/api/reviews', function(req, res) {
console.log("fetching reviews");
// use mongoose to get all reviews in the database
Review.find(function(err, reviews) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err)
res.json(reviews); // return all reviews in JSON format
});
});

答案 0 :(得分:1)
我遇到了同样的问题,使用mongoimport绕过架构并使架构类型检查和验证无效。所以,我所做的对于单个json对象来说效果很好。我打算将它扩展到整个json文件。所以,我有一个POST请求,它将数据添加到通过模式的mongoDB中。我制作了一个curl脚本来制作相同的帖子请求并完成模式。这是我的卷曲脚本。
curl \
--header "Content-type: application/json" \
--request POST \
--data @data.json \
http://localhost:3000/supplierList
我在data.json文件中有一个json对象。这是它的样子。
{
"supplierName": "KINGCOBRA",
"price": "12345678911234567.00000000000000001",
"basicDate": "2045/03/23",
"currency": "USD",
"partName": "ASDF",
"description": "First Object: TEST 1: POST Inserting an array of object through the script",
"volume": 2334
}
这种方法的唯一问题是它不支持json数组的插入。但它适用于单个对象而不管它的大小。如果有人找到了解决方法,请告诉我。