Home > Enterprise >  save an array of objects to MongoDB with Mongoose on Javascript
save an array of objects to MongoDB with Mongoose on Javascript

Time:08-28

I have this data (json):

  var unique = 
  [
  {"name":"John", "number":"4132321234"}, 
  {"name":"Jack", "number":"451232421234"}, 
  {"name":"Maddy", "number":"12314124"}, 
  {"name":"Alex", "number":"213468316"}
  ]

What I want to do, is save this data to my mongoDB collection, with the following schema (using mongoose):

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const nameSchema = new Schema({

    name: {
        type: String,
        required: true,
    },
    number: {
        type: String,
        required: true,
    },
   

});

const Name_db = mongoose.model('Name_db', nameSchema)
module.exports = Name_db;

I wrote a loop, to attempt to do this:

 for (var k = 1; k < unique.length; k  ) {
    var name_mongo = new Name_db({
       name: unique[k].name,
        number: unique[k].number,
      
       },
      )
      console.log(unique[k].name)
     
  
    }   name_mongo.save()
    .then(results => {
     res.send(results)
     })
     .catch(err => {
       console.log(err);})

This doesn't work because right now it is only sending data once to mongo DB, meaning only of the arrays is actually being sent over, instead of all 3 of them being sent to mongoDB.

Would appreciate any help, thank you for the time.

CodePudding user response:

Name_db.insertMany(unique)
    .then((result) => console.log("Inserted", result))
    .catch((error) console.log(error));

or

const result = await Name_db.insertMany(unique); // remember to decorate the function async
  • Related