如何将json对象数组保存到猫鼬?
Posted
技术标签:
【中文标题】如何将json对象数组保存到猫鼬?【英文标题】:How to save array of json object to mongoose? 【发布时间】:2017-06-09 14:47:24 【问题描述】:我正在尝试将对象数组保存到猫鼬模式,但无法将数据加载到laptop
模式中,我只看到一个包含id
的插入。
如何将 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);
【问题讨论】:
检查Storing Json Object in Mongoose String key 请在此处发布用户猫鼬模式以帮助调试 @georoot 架构添加到问题 【参考方案1】:您应该单独创建对象并保存它们。你不能传递这样的数组。在行中使用一些东西
var laptopData = [...];
for(var laptopItem in laptopData)
new Laptop(laptopData[laptopItem])
.save()
.catch((err)=>
console.log(err.message);
);
【讨论】:
不错且简单的方法:)以上是关于如何将json对象数组保存到猫鼬?的主要内容,如果未能解决你的问题,请参考以下文章