2

I am trying to save array of object to mongoose schema but it is failing to load data into laptop schema i only see one insertion that contains id. How can i save array of json object to mongoose schema ?

controller.js

var laptopData = [
{ name: 'Hp probook 15.1',cpu:'2.4GHZ' ,ram: '4GB', harddrive: '160GB',Brand:'HP'},
{ name: 'Hp probook 15.1',cpu:'2.4GHZ' ,ram: '4GB', harddrive: '160GB',Brand:'Hp'},
{ name: 'Hp probook 15.1',cpu:'2.4GHZ' ,ram: '4GB', harddrive: '160GB',Brand:'Hp'},
{ name: 'Hp probook 15.1',cpu:'2.4GHZ' ,ram: '4GB', harddrive: '160GB',Brand:'Hp'},
{ name: 'Hp probook 15.1',cpu:'2.4GHZ' ,ram: '4GB', harddrive: '160GB',Brand:'Hp'},
{ name: 'Hp probook 15.1',cpu:'2.4GHZ' ,ram: '4GB', harddrive: '160GB',Brand:'Hp'},
{ name: 'Hp probook 15.1',cpu:'2.4GHZ' ,ram: '4GB', harddrive: '160GB',Brand:'HP'},
{ name: 'Hp probook 15.1',cpu:'2.4GHZ' ,ram: '4GB', harddrive: '160GB',Brand:'Hp'},
{ name: 'Hp probook 15.1',cpu:'2.4GHZ' ,ram: '4GB', harddrive: '160GB',Brand:'Hp'},
{ name: 'Hp probook 15.1',cpu:'2.4GHZ' ,ram: '4GB', harddrive: '160GB',Brand:'Hp'},
{ name: 'Hp probook 15.1',cpu:'2.4GHZ' ,ram: '4GB', harddrive: '160GB',Brand:'Hp'}
]
var laptop = new Laptop({laptopData});
laptop.save(function(err) {
  // we've saved the dog into the db here
  if (err) throw err;

});

schema.js

'use strict';

var mongoose = require('bluebird').promisifyAll(require('mongoose'));

var LaptopSchema = new mongoose.Schema({
  name: String,
  ram:String,
  harddrive:String,
  Brand: String
});

module.exports = mongoose.model('Laptop', LaptopSchema);
3
  • check Storing Json Object in Mongoose String key Commented Jan 24, 2017 at 17:19
  • Please post user mongoose schema also over here to help debug Commented Jan 24, 2017 at 18:19
  • @georoot schema added to question Commented Jan 24, 2017 at 19:51

1 Answer 1

4

You should individually create objects and save them. You can't pass an array like that. Use something in the lines of

var laptopData = [...];
for(var laptopItem in laptopData){
    new Laptop(laptopData[laptopItem])
      .save()
      .catch((err)=>{
        console.log(err.message);
      });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice and easy approach :)

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.