【问题标题】:why doesn't mongoose save my model为什么猫鼬不保存我的模型
【发布时间】:2017-01-04 21:10:02
【问题描述】:

我有这个 node.js 代码,它将一组文本数组保存到托管在 mongolab.com 的 MongoDB 中。我使用 Mongoose ORM 并注意到代码连接到数据库但没有执行保存方法。

function save2Db(texts) {
    var db = require('mongoose');
    db.Promise = global.Promise;
    db.connect('mongodb://user:pswd@ds013456.mlab.com:13456/heroku_xxxxxxx');
    db.connection.on('error', console.error.bind(console, 'connection error!'));
    db.connection.on('close', console.error.bind(console, 'closed db!'));
    db.connection.once('open', function() {
        console.log('opened db!');

        /* Create schema */
        var textSchema = new db.Schema({
            date: { type: Date, default: Date.now },
            text: [String]
        });

        /* Create model */
        var TextModel = db.model('Text', textSchema, 'testCollection');

        /* Save data to database */
        texts.forEach(function(content) {

            console.log(`saving ${content}`);

            var t = new TextModel({text : content});

            t.save(function (err) {
                console.log('inside t.save');
                if (err) {
                    console.error(err);
                } else {
                    console.log('Saved to db');
                }
            }); //t.save
        }); // texts.forEach

        db.connection.close();
    });
}

save2Db([['a','b'],['c'],['d','e','f','g']])

得到输出

opened db!
saving a,b
saving c
saving d,e,f,g
closed db!

你知道为什么保存方法不起作用吗?谢谢。

【问题讨论】:

    标签: node.js mongodb heroku mongoose


    【解决方案1】:

    t.save 是一个异步函数。您正在关闭数据库的连接,然后才能运行保存。如果要关闭数据库连接,则需要等到所有保存回调都被调用。我建议为此使用 Promise。

    function save2Db(texts) {
        var db = require('mongoose');
        db.Promise = global.Promise;
        db.connect('mongodb://user:pswd@ds013456.mlab.com:13456/heroku_xxxxxxx');
        db.connection.on('error', console.error.bind(console, 'connection error!'));
        db.connection.on('close', console.error.bind(console, 'closed db!'));
        db.connection.once('open', function() {
            console.log('opened db!');
    
            /* Create schema */
            var textSchema = new db.Schema({
                date: {
                    type: Date,
                    default: Date.now
                },
                text: [String]
            });
    
            /* Create model */
            var TextModel = db.model('Text', textSchema, 'testCollection');
    
            /* Save data to database */
            var saves = [];
            texts.forEach(function(content) {
    
                console.log(`saving ${content}`);
    
                var t = new TextModel({
                    text: content
                });
                saves.push(t.save());
            });
            Promise.all(saves)
                .then(() => db.connection.close())
                .catch(err => {
                  console.log(err);
                  db.connection.close();
                });
        });
    }
    

    一些附加说明:您应该将数据库启动部分移出save2Db 函数,因为每次您想要保存某些内容时都会调用它。您也不必等到连接打开,因为您的猫鼬模型无论如何都会这样做。最后但同样重要的是:如果您一直在进行 db 调用,则无需连接和关闭数据库连接。只需连接一次并保持打开状态。

    【讨论】:

    • 谢谢。直到你说,我才注意到保存是异步的。
    猜你喜欢
    • 2020-09-05
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 2014-05-27
    • 2016-06-29
    • 1970-01-01
    相关资源
    最近更新 更多