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

时间:2017-10-27 04:50:59

标签: node.js mongodb express mongoose mongoose-schema

我对Web开发很新,来自java / android背景。我读了所有其他所有关于mongoose save()的问题没有保存到db但仍然无法将其写入db。

谢谢!

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

  
    

节点groceryQueries.js插入fruits,apple,appl.jpg,.46

  

这是输出:

  

(节点:14548)弃用警告:open()在mongoose> = 4.11.0中已弃用,请改用openUri(),或者如果使用useMongoClient则设置connect()选项或createConnection()。见http://mongoosejs.com/docs/connections.html#use-mongo-client

     

连接到mongodb

     

params:fruits,apple,appl.jpg,.46   (node:14548)DeprecationWarning:不推荐使用Mongoose:mpromise(mongoose的默认承诺库),而是插入自己的promise库:http://mongoosejs.com/docs/promises.html

     

保存苹果

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>')
}
}

2 个答案:

答案 0 :(得分:1)

save会返回一个您必须等待的承诺:

        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()

答案 1 :(得分:0)

代码中的主要问题是您在保存之前关闭了与db的连接。请注意,mongoose中的所有数据库操作都是异步的,调用异步函数只是为事件循环的下一个时钟周期调度操作。

你想这样做:

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

从保存后的挂钩中删除next,该参数实际上是保存的杂货,您不应该像函数一样调用它。

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

<强>加成

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

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

要删除有关promises的警告,请在需要mongoose之后添加:

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