0

I have two arrays, one contain keys and other the values. I want to insert key value pairs in mongodb.

var keys = ["item1","item2","item3"];
var values = ["15","14","19"];

I am using insertOne to enter the key value pairs into the database.

MongoClient.connect('mongodb://localhost:27017/Clients', (err,db) => {
    if(err)
        {
        return console.log('Unable to Connect');
        }
    console.log('Connected to Mongodb server');

    for(var i=0,l=keys.length; i<l;i++)
    {

       db.collection('Orders').insertOne({
       keys[i] : values[i]
        }, (err,result) => {
            if(err)
                {
                    return console.log(err);
                }
       });
    }
    db.close();    
});


**

**

Error:  keys[i] : values[i]
                   ^

        SyntaxError: Unexpected token [

**

**

Where am I wrong? Is there any other way to complete this task ? Any help is appreciated.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • 1
    `[keys[i]] : values[i]` You are missing wrapping brackets `[]` on the "key" – Neil Lunn Apr 27 '18 at 21:31
  • Also, shorten your code. The loop is not necessary. `db.collection('orders').insertMany( keys.map((k,i) => ({ [k]: values[i] })), (err,result) => { if (err) throw err; db.close() })` and of course you need to understand async calls. Your code ( when corrected ) will hang up the database before the loop is complete. My line of code inserts everything with no loop, and only "closes" **within** the callback argument. – Neil Lunn Apr 27 '18 at 21:40

0 Answers0