【问题标题】:Data seeded with Mongoose not being saved in MongoDB使用 Mongoose 播种的数据未保存在 MongoDB 中
【发布时间】: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 中返回给我有什么原因吗?

标签: node.js mongodb mongoose


【解决方案1】:

在您尝试保存产品之前,您是否知道 Mongoose 是否已成功连接?

一种想法可能是,由于 Db 访问是异步的,因此您试图在连接存在之前保存项目。

您可以将回调传递给您的连接或使用事件侦听器并将保存函数包装在连接回调中。

mongoose.connection.on('connected', function(){
  //save products here
});

我读过一些 Mongoose 无法正确保存的案例。

编辑:听.on('open') 而不是(mongoose docs) 可能会更好。

【讨论】:

  • 当您在mongo shell 中并输入use shoppingshow collections 时,您看到products 集合了吗?你能发布你正在使用的猫鼬模型代码吗?我在与 YouTube 视频相关的存储库中找不到它。
  • 刚刚用模型代码更新了原帖。当我输入show collections 时,我看到Product
  • 我知道集合是区分大小写的...db.Product.find() 能给你什么吗?
  • 哦,解决了!我认为集合总是小写和复数,所以如果我创建一个名为 Product 的模式,那么集合应该是产品吗?
  • Looks like it! Mongoose 将根据模型名称自动将集合名称小写和复数,除非您使用 mongoose.model 中的第三个参数覆盖此行为:module.exports = mongoose.model('Product', schema, 'products'); // db.products.find() would now work
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-10
  • 2018-06-27
  • 1970-01-01
  • 2021-09-01
  • 1970-01-01
  • 2017-07-27
  • 2023-03-23
相关资源
最近更新 更多