猫鼬保存功能不起作用。 post('save') 没有被调用但没有错误

mongoose save function not working. post('save') not getting called but no error

我是 Web 开发的新手,并且有 java/android 背景。我阅读了所有其他有关 mongoose save() 不保存到数据库的问题,但仍然无法将其写入数据库。

谢谢!

我写了 grocery.js 来定义我的模式,我写了另一个脚本 groceryQueries.js 来写入和读入数据库。调用保存预挂钩,但不调用保存后挂钩。这是我使用的命令:

node groceryQueries.js insert fruits,apple,appl.jpg,.46

这是输出:

(node:14548) DeprecationWarning: open() is deprecated in mongoose >= 4.11.0, use openUri() instead, or set the useMongoClient option if using connect() or createConnection(). See http://mongoosejs.com/docs/connections.html#use-mongo-client

connected to mongodb

params: fruits,apple,appl.jpg,.46 (node:14548) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html

saving apple

grocery.js:

var mongoose = require('mongoose');

var grocerySchema = new mongoose.Schema({
    name: {
        type: String,
        unique: false,
        required: true,
        trim: true
    },
    img: {
        type: String,
        unique: false,
        required: false,
        trim: true
    },
    price: {
        type: Number,
        unique: false,
        required: true,
        trim: true
    },
    category: {
        type: String,
        unique: false,
        required: true,
        trim: true
    }
});

grocerySchema.pre('save',function(next) {
    var grocery = this;
    console.log("saving "+grocery.name);
    next();
});
grocerySchema.post('save',function(next) {
    console.log("post saving ");
    next();
});

grocerySchema.statics.COLLECTION_NAME = function() {
    return 'groceries';
}

grocerySchema.methods.toString = function() {
    console.log(Grocery.COLLECTION_NAME() + ", Category: " + this.category + " is " + this.name+" and costs "+this.price+"");
};

var Grocery = mongoose.model('groceries',grocerySchema);
module.exports = Grocery;

groceryQueries.js:

var mongoose = require('mongoose');
var url = "mongodb://localhost:27017/deliveryservice";
mongoose.connect(url);
const Grocery = require('../server/models/grocery');

var db = mongoose.connection;
db.on('error',console.error.bind(console,'connection error'));
db.once('open',function() {
    console.log("connected to mongodb");
    doQueries();
});

function doQueries() {
var groceryCollection = Grocery.COLLECTION_NAME();//"groceries";
var arg = process.argv[2];

if (arg == 'find' ||
    arg == 'insert') {
        if (arg == 'find') {
            var nameArg = process.argv[3];
            if (nameArg === undefined) {
                var error = new Error('undefined name');
                throw error;
            }
            Grocery.find({name: nameArg},function(err,groceries) {
                if (err) {
                    return console.error(err);
                }
                console.log("groceries: " + groceries);
                db.close();
            });
        } else if (arg == 'insert') {
            var paramsArg = process.argv[3];
            var throwError = false;
            if (paramsArg === undefined) {
                throwError = true;
            }
            console.log("params: "+paramsArg);
            var parameters = paramsArg.split(",");
            if (parameters.length != 4) {
                throwError = true;
            }
            if (throwError) {
                var error = new Error('undefined parameters <name>,<img>,<price>');
                throw error;
            }
            var newGrocery = new Grocery({category: parameters[0],name: parameters[1], img: parameters[2], price: parameters[3]});
            //console.log("before save: "+newGrocery.toString());
            newGrocery.save(function(err,newGrocery) {
                if (err) {
                    throw err;
                }
                grocery.toString();
            });
            db.close();
        }
} else {
    console.log('help: find <name> | insert <category>,<name>,<img>,<price>')
}
}

save returns一个承诺,你必须等待:

        newGrocery.save(function(err,newGrocery) {
            if (err) {
              console.log(err);
                throw err;
            }
            newGrocery.toString();  // you had a typo here btw
        }).then(function() { db.close();});

你的代码在 mongoose 有机会保存任何东西之前运行 db.close()

您代码中的主要问题是您在保存之前关闭了与数据库的连接。请注意,猫鼬中的所有数据库操作都是异步的,调用异步函数只是为事件循环的下一个滴答安排操作。

您想这样做:

newGrocery.save(function(err, newGrocery) {
  if (err) {
    throw err;
  }
  // grocery.toString(); <- typo here btw, param is called newGrocery
}).then(function() {
  db.close();
});

并从你的 post-save 挂钩中删除 next,该参数实际上是保存的杂货店,你不应该像函数一样调用它。

grocerySchema.post('save', function() {
  console.log('post saving ');
})

奖金

要消除关于 open() 和 connect() 被弃用的警告,请使用它来选择加入新的连接逻辑:

mongoose.connect(url, {
  useMongoClient: true,
});

要消除关于 promises 的警告,请在 require mongoose 之后添加:

// Use native promises
mongoose.Promise = global.Promise