这是我的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的本地主机中保存数据?
答案 0 :(得分:0)
就像@Neil Lunn提到的那样,您可以使用Mongoose.insertMany
插入多个文档。将您的产品数组更改为对象并将其传递给Product.insertMany,就像我在下面所做的那样:
var products = [{
imagePath: 'https://d28dwf34zswvrl.cloudfront.net/wp-content/uploads/2016/08/125-fall-in-love.png',
title: '',
discription: 'Awesome Game!!',
price: 10
},
{
imagePath: 'http://www.accounting-coach.com/wp-content/uploads/2016/12/product.jpg',
title: '',
discription: 'Amet sint tempor enim cupidatat.',
price: 20
},
{
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
},
{
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
},
{
imagePath: '',
title: '',
discription: 'Amet sint tempor enim cupidatat.',
price: 50
}];
Product.insertMany(products, function(error, docs) {
if (error)// do something with error
// do something with docs, etc
if (docs.length === products.length) exit();
});