0

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.

1
  • 2
    You can't just use insertMany function? Commented Aug 27, 2022 at 10:12

1 Answer 1

1
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
Sign up to request clarification or add additional context in comments.

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.