2

I am trying to pre-load array of objects to MongoDB as below:

the below code works if I do one object at a time. that is,

if I set:

tmp_obj = { 
  id:1, 
  name: 'Tmp 1' 
}

model file

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var TmpSchema   = new Schema({
    id: Number,
    name: String
});


var Tmp= mongoose.model('Tmp', TmpSchema);
module.exports = Tmp;

routes file

var express = require('express');
var router = express.Router();
var Tmp = require('../models/tmp');


var tmp_obj = [
  { 
    id:1, 
    name: 'Tmp 1' 
  },
  { 
    id:2, 
    name: 'Tmp 2' 
  },
  { 
    id:3, 
    name: 'Tmp 3' 
  }
];

var tmp = new Tmp(tmp_obj);

tmp.save(function (err) {
  if (err) return console.log(err);

  console.log('tmp saved to the database');
  return res.redirect('/login');
})

how do I push an array of objects to the mongo? and also I have multiple collections to add. so, do I do something like:

tmp1.save(function (err) {
  if (err) return console.log(err);

  console.log('tmp1 saved to the database');

  tmp2.save(function (err) {
    if (err) return console.log(err);

    console.log('tmp2 saved to the database');
    return res.redirect('/login');
  })
})

2 Answers 2

3

Another alternative is to use .create() method, it could accept an array of objects or a single object, and you don't need to create a model instance (i.e var tmp = new Tmp(tmp_obj);), here is an example:

var Tmp = require('../models/tmp');

var tmp_obj = [
    { id:1, name: 'Tmp 1' },
    { id:2, name: 'Tmp 2' },
    { id:3, name: 'Tmp 3' }
];

Tmp.create(tmp_obj, function (err, temps) {

    if (err) {
        console.log(err);
        // terminate request/response cycle
        return res.send('Error saving');
    }

    res.redirect('/login');

});

One last thing, don't forget to terminate the request/response cycle if an error has been occurred, otherwise the page will hangs

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the method insertMany from mongoose to insert multiple document at once.

From the documentation of mongoose v5.0.4

var arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }];

Movies.insertMany(arr, function(error, docs) {});

An alternative using .save() would be

// Create all objects
const objects = tmp_obj.map(x => new Tmp(x));

try {
   // Saves objects
   const docs = await Promise.all(objects.map(x => x.save()));
} catch(e) {
  // An error happened
}

But you should not use it since insertMany is way better

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.