【发布时间】:2017-06-19 15:38:17
【问题描述】:
这是我的所有代码的 js 文件。
var Product = require('../models/product');
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('localhost:27017/shopping');
var products = [
new Product({
imagePath: 'https://d28dwf34zswvrl.cloudfront.net/wp-content/uploads/2016/08/125-fall-in-love.png',
title: '',
discription: 'Awesome Game!!',
price: 10
}),
new Product({
imagePath: 'http://www.accounting-coach.com/wp-content/uploads/2016/12/product.jpg',
title: '',
discription: 'Amet sint tempor enim cupidatat.',
price: 20
}),
new Product({
imagePath: 'https://www.gs1us.org/portals/0/Images/02_UPCs_Barcodes_and_Prefixes/02-1-2_Choose_Product_GTIN_or_Location_GLN_Identification/02-1-2-module-data-hub-product-video@1x.png',
title: '',
discription: 'Amet sint tempor enim cupidatat.Amet sint tempor enim cupidatat.Amet sint tempor enim cupidatat.',
price: 30
}),
new Product({
imagePath: 'https://www.acesled.com/wp-content/uploads/2015/01/Prod02.png',
title: '',
discription: 'Amet sint tempor enim cupidatat.Amet sint tempor enim cupidatat.Amet sint tempor enim cupidatat.',
price: 40
}), new Product({
imagePath: '',
title: '',
discription: 'Amet sint tempor enim cupidatat.',
price: 50
})
];
var done = 0;
for (var i = 0; i < products.length; i++) {
products[i].save(function(err, result) {
done++;
if (done === products.length) {
exit();
}
});
}
function exit() {
mongoose.disconnect();
}
我的所有架构都在首先导入的模型文件夹中。
我做了一个数组,把所有的数据一一保存by using save method of mongoose
我正在使用 for 循环来保存数组中的所有数据。一切都很好,但是当我在我的 cmd 中运行 show DBS 时。没有名称购物的数据库。
谁能帮我吗?如何将数据保存在我的 MongoDB 本地主机中??
【问题讨论】:
-
解决了!!描述字段中有拼写错误,所以我使用了..
-
products[i].save(function(err, result) { if (err) console.log(err); done++; if (done === products.length) { console.log( '保存'); 退出(); }
-
您还应该学习使用
.create()或更好的.insertMany(),它可以在没有循环的情况下完成您所做的一切。