尝试使用唯一索引保存mongoose文档时,节点服务器崩溃

时间:2014-07-03 21:02:18

标签: node.js mongodb mongoose unique

我有一个集合,其中一个字段作为唯一字段。

var ProductSchema = new mongoose.Schema({
     code:          {type:String, required:true},
     name:          {type:String, default:""}
});

ProductSchema.index({ code: 1}, { unique: true });

当我使用已存在的代码创建新文档时,服务器崩溃而不是通过回调返回错误:

module.exports.create = function (params, callback){

    var product = new ProductModel(params);
    product.save(function(error){
         console.log(error);
         callback(error);
    });
}

这是(崩溃)预期的行为还是mongoose应该通过回调返回错误而不是崩溃?

这是使用相同代码保存第二个文档时出现的错误:

[..path]/server/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js:245
        throw message;      
              ^
TypeError: Cannot read property '0' of undefined
    at [...path]/server/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/core.js:114:55
    at [...path]/server/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1132:7
    at [...path]/server/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1846:9
    at Server.Base._callHandler ([...path]/server/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js:445:41)
    at [...path]/server/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:478:18
    at MongoReply.parseBody ([...path]/server/node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:68:5)
    at null.<anonymous> ([...path]/server/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:436:20)
    at EventEmitter.emit (events.js:95:17)
    at null.<anonymous> ([...path]/server/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:201:13)
    at EventEmitter.emit (events.js:98:17)

1 个答案:

答案 0 :(得分:1)

http://mongoosejs.com/docs/api.html#model_Model-save

直接在产品保存上设置错误处理程序:

ProductModel.on('error', function(){..});