【发布时间】:2018-06-11 06:53:07
【问题描述】:
我正在尝试使用 Mongoose 向 MongoDB 添加一些数据,但是我无法将这些数据保存到我的数据库中。我正在关注 YouTube 上的 this 教程(约 11 分钟),但我认为该视频可能使用了不同版本的 Mongoose。
基本上,我在一个单独的 JS 文件中定义了一个 Product 架构,并且我正在运行一个名为 productSeeder.js 的文件,方法是在终端中运行 node productSeeder.js 并运行 Mongo 守护程序。当我切换到正确的数据库并在 Mongo shell 中键入 db.products.find() 时,没有任何返回给我。
我的 productSeeder.js 文件:
var Product = require('../models/product');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/shopping');
var products = [
new Product({
imagePath: 'images/dummy.png',
price: 9,
title: 'a title',
desc: 'some text'
}),
new Product({
imagePath: 'images/dummy.png',
price: 5,
title: 'a title',
desc: 'some text'
})
];
var done = 0;
for (var i = 0; i < products.length; i++) {
products[i].save(function(err, result) {
if (err) {
console.log(err);
return;
};
done++;
if (done == products.length) {
mongoose.disconnect();
};
});
};
我的 product.js 文件:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
imagePath: {type: String, required: true},
price: {type: Number, required: true},
title: {type: String, required: true},
desc: {type: String, required: true}
});
module.exports = mongoose.model('Product', schema);
非常感谢,节日快乐!
【问题讨论】:
-
控制台没有错误?你有没有尝试使用console.log或者调试保存回调返回的结果值,它包含什么?
-
没有错误;我尝试打印结果,它打印了正确的产品。
-
刚刚将 Product.find({}, function(err, products) { console.log(products.length) }) 添加到我的代码中,在
if done;出于某种原因,每次运行整个文件时长度都会增加,这意味着实际上正在保存数据?那么,数据没有在 MongoDB shell 中返回给我有什么原因吗?