gpt4 book ai didi

node.js - 尝试使用唯一索引保存 Mongoose 文档时, Node 服务器崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 01:04:15 24 4
gpt4 key购买 nike

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

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)

最佳答案

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

直接在产品的保存中放置错误处理程序:

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

关于node.js - 尝试使用唯一索引保存 Mongoose 文档时, Node 服务器崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24563253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com