N
N
No Name2016-12-08 22:35:47
MongoDB
No Name, 2016-12-08 22:35:47

Mongoose: how to save multiple documents with one request?

There is a code that should save several documents at once:

app.post('/createTestUsers', (request, response) => {
  let data = [
    {name: 'Mike'},
    {name: 'Tom'}
  ];
  User.collection.insert(data, (err, doc) => {
    if(err) {
      console.log('/createTestUsers | POST | Error was occurred');
      console.log(err.errmsg);
      response.status(403).send(err.errmsg);
    }
    if(!err) {
      response.status(200).send(amount + ' users was created');
    }
  });
});

But only the first document appears in the database, and an error is displayed in the console:
E11000 duplicate key error collection: contacts_ng2.users index: login_1 dup key: { : null }

I did it like stackoverflow.com/a/24848148
but it doesn't work

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton L, 2016-12-09
@alienworkshop

You have a duplicate key field login_1. Modify each object in the doc array by adding a unique login_1 property.
let data = [
{name: 'Mike', login_1: 'mikeLogin' },
{name: 'Tom', login_1: 'tomLogin'}
];
Or don't use indexing on login_1.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question