2017-01-24 82 views
1

我試圖將對象數組保存到貓鼬模式,但它無法將數據加載到laptop模式我只看到一個包含id的插入。 如何將json對象的數組保存爲mongoose模式?如何將json對象的數組保存爲貓鼬?

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); 
+0

檢查[存儲JSON對象在貓鼬字符串鍵]行(http://stackoverflow.com/questions/17497875/storing-json-object-in-mongoose-string-key) – yaitloutou

+0

請在這裏發佈用戶mongoose模式以幫助調試 – georoot

+0

@georoot模式添加到問題 – hussain

回答

1

你應該單獨創建對象並保存。你不能像這樣傳遞數組。使用的東西在

var laptopData = [...]; 
for(var laptopItem in laptopData){ 
    new Laptop(laptopData[laptopItem]) 
     .save() 
     .catch((err)=>{ 
     console.log(err.message); 
     }); 
} 
+0

感謝它幫助我解決。 – hussain