Mongoose导入Json导出和ID
我想为单元测试导入实际数据库的固定有限子集。因此,我将带有mongo shell的数据库导出到mydata.json中。现在我想将这个JSON文件数组准确地读入我的数据库,同时保留ID 1st:我已经无法读取JSON导出,如何修复Mongoose导入Json导出和ID,json,mongodb,Json,Mongodb,我想为单元测试导入实际数据库的固定有限子集。因此,我将带有mongo shell的数据库导出到mydata.json中。现在我想将这个JSON文件数组准确地读入我的数据库,同时保留ID 1st:我已经无法读取JSON导出,如何修复 if !db? mongoose.connect(configDB.url,{auth:{authdb:configDB.authdb}}, (err)-> if (err) console.log(err) ) db = mon
if !db?
mongoose.connect(configDB.url,{auth:{authdb:configDB.authdb}}, (err)->
if (err)
console.log(err)
)
db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', () ->
console.log "Database established"
#Delete all data and seed new data
SomeModel = require(applicationDir + 'node/models/some.model.js')
SomeModel.remove({}, (err) ->
console.log('collection somes removed seeding new one')
fs.readFile(__dirname + '/../../mongo/seed-for-test/somes.json','utf-8', (err,fileData) ->
console.log typeof fileData
fileData = JSON.parse(fileData)
console.log fileData.length
# new SomeModel(fileData).save((err) ->
# if err?
# return console.log err
# console.log('somes saved')
# )
)
)
)
错误
string
undefined:2
{ "_id" : { "$oid" : "551d82e30287751fa2f2dfb2" }, "prooven" : true, "title" :
^
SyntaxError: Unexpected token {
at Object.parse (native)
at /Users/MasterG/Desktop/PROJEKTE/lek/specs/backend/mongo.service.spec.js:37:27
at fs.js:336:14
at /Users/MasterG/Desktop/PROJEKTE/lek/node_modules/wiredep/node_modules/bower-config/node_modules/graceful-fs/graceful-fs.js:104:5
at FSReqWrap.oncomplete (fs.js:99:15)
第二名
如果我取消注释下半部分,它会工作吗,或者还有什么我需要做的
编辑
导出不会返回json对象的有效数组。导出时必须使用
--jsonArray
标志。这适用于使用--jsonArray
标志进行导出,但在我看来这是错误的。而且.json文件的格式也没有以前那么好。我需要添加一些额外的逻辑来检查是否保存了最后一个条目
ObjectId = require('mongoose').Types.ObjectId
SomeModel = require(applicationDir + 'node/models/some.model.js')
if !db?
mongoose.connect(configDB.url,{auth:{authdb:configDB.authdb}}, (err)->
if (err)
console.log(err)
)
db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', () ->
console.log "Database established"
#Delete all data and seed new data
SomeModel.remove({}, (err) ->
console.log('collection somes removed seeding new one')
fs.readFile(__dirname + '/../../mongo/seed-for-test/somes.json','utf-8', (err,fileData) ->
fileData = JSON.parse(fileData)
for singleFileData in fileData
singleFileData._id = new ObjectId(singleFileData._id.$oid)
new SomeModel(singleFileData).save((err) ->
if err?
return console.log err
console.log('somes saved')
)
)
)
)