Saturday 25 January 2020

How to add json Array of subdocuments into MongoDB?

Hi,Just dipping my toe into MEAN with a small project to see how I can start using node and mongo instead of our normal c#, IIS and SQL server.I'm slowly getting my head around the NOSQL way but I'm stuck at what I think should be a pretty easy thing. I have written a model that has a main shema and a 2nd schema that will be subdocuments.​const mongoose = require('mongoose'); const batchDetailsSchema = mongoose.Schema({ account: {type:Number, required: true}, project: {type:String, required: true}, description: String, amount: {type:Number, required:true}, extRef: String }); const batchSchema = mongoose.Schema({ batchID: String, description: String, uploadedBy: Number, uploadedDate: { type:Date, default: Date.now() }, batchDetails: [batchDetailsSchema] }); module.exports = mongoose.model('Batch', batchSchema) I have a user upload a csv file, this file matches the batchDetailsSchema, and it contains 3000 rows.I have the csv file convert to a json object but I can't work out how to add all of these objects in one go as subdocuments of the batch.​I have it working for one using push:Batch.findOne({"_id" : newBatchID}, (err, doc)=>{ doc.batchDetails.push({ account: results[0]['account'], project: results[0]['project'], description: results[0]['description'], amount: restults[0]['amount'], extref: results[0]['extref'] }) doc.save(); So I suppose I could loop through each row of the csv and add it this way but that's 3000 calls to the database when I am sure I'm missing the simple way to just use the jsonObject.Any help would or links links to some decent tutorials but be really appreciated.Cheers

Submitted January 25, 2020 at 10:48AM by aBitOfCloud

No comments:

Post a Comment