Blackhat
Blackhat

Reputation: 39

How to save an array of object in mongo db using mongoose

Giving the following snippets of object below:

var s;
var tab = [];
var myarray= [];
for(var i=0;i<=tab.length-1;i++){
              s= "{\"id\":\"" + tab[i][0] + "\",\"ts\":\"" + tab[i][1] + "\",\"lat\":\"" + tab[i][2] + "\",\"lon\":\""+tab[i][3]+"\"}";
                myarray.push(s);
            }

myarray = [ '{"id":"id1","ts":"ts1","lat":"lat1","lon":"lon1"}',
  '{"id":"id2","ts":"ts2","lat":"lat2","lon":"lon2"}',
  '{"id":"id3","ts":"ts3","lat":"lat3","lon":"lon3"}' ]

I want to save it in mongo database by using mongoose, this is my code:

for(var obj in myarray){
       var doc = new MyCollection(myarray[obj])
        doc.save()
                  .catch((err=>{console.log(error.message);}))
            }

But I get this error when executing the code:

TypeError: Cannot use 'in' operator to search for '_id' in {"id":"id1","ts":"ts1","lat":"lat1","lon":"lon1"}

I don't find the source of the error. Can you help me please?

Upvotes: 0

Views: 54

Answers (3)

Blackhat
Blackhat

Reputation: 39

I got solution by doing this:

for(var i=0;i<=tab.length-1;i++){
              s= "{\"id\":\"" + tab[i][0] + "\",\"ts\":\"" + tab[i][1] + "\",\"lat\":\"" + tab[i][2] + "\",\"lon\":\""+tab[i][3]+"\"}";
                myarray.push(JSON.parse(s));
            }

So i just parsed the s string!

Upvotes: 0

Rupali Pemare
Rupali Pemare

Reputation: 540

Hope this helps

 var myarray = [ {"id":"id1","ts":"ts1","lat":"lat1","lon":"lon1"}',
        '{"id":"id2","ts":"ts2","lat":"lat2","lon":"lon2"}',
        '{"id":"id3","ts":"ts3","lat":"lat3","lon":"lon3"} ];

    Model.create(myarray, function (err) {
        if (err) {
            response.send({error: true, message: err});
        } else {
            response.send({success: true});
        }
    });

Upvotes: 0

Dinesh undefined
Dinesh undefined

Reputation: 5546

in myarray you have enclosed object using single quotes.remove it and try. your myarray should be like this.

myarray: [ {"id":"id1","ts":"ts1","lat":"lat1","lon":"lon1"}',
  '{"id":"id2","ts":"ts2","lat":"lat2","lon":"lon2"}',
  '{"id":"id3","ts":"ts3","lat":"lat3","lon":"lon3"} ];

for(var obj in myarray){
       var doc = new MyCollection(myarray[obj])
        sigfoxData.save()
                  .catch((err=>{console.log(error.message);}))
            }

Upvotes: 1

Related Questions