我应该在哪里抓住这个Promise MongoError?
我升级了我的mongoose,所以当然我开始得到这些:
DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
所以我加了mongoose.Promise = global.Promise
。 都好。 除了…现在我得到这个人:
(node:20760) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: exception: Index with name: stampRoundedToNearestHour_1 already exists with different options (node:20760) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
修复底层错误是很容易的,但是我不知道应该在哪里捕获它,以便将来的Node版本在遇到类似的情况时不会突然崩溃。 我已经产生了我的代码的最小版本,产生错误。 这是一个JavaScript文件:
var mongoose = require('mongoose') mongoose.Promise = global.Promise var TestSchema = mongoose.Schema({ num: Number, }) TestSchema.index({'num': 1}, { sparse: true }) TestSchema.index({'num': 1}, { sparse: false }) // The above line is deliberately designed to be problematic. // My question isn't how to not get an error, // it's that I don't know where to catch it when I do! // If this line is commented out, there's no error // but it doesn't return a promise, so I can't .then or .catch on it var Test = mongoose.model('Test', TestSchema) mongoose.connect(process.env.MONGOLAB_URI, {useMongoClient: true}) .then(function () { console.log("mongoose.connected successfully") }).catch(function (err) { console.log("mongoose.connect catch", err) })
正如你所看到的,我在mongoose.connect()
函数上尝试了两种error handling,但是当我运行这个时输出的是
mongoose.connected successfully (node:26795) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: exception: Index with name: num_1 already exists with different options (node:26795) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
我已经尝试添加.catch(...)
字面上每一个其他的function在这里:
-
mongoose.Schema(...)
-
TestSchema.index({'num': 1}, { sparse: true })
-
mongoose.model('Test', TestSchema)
- 甚至
require('mongoose')
(这感觉愚蠢的,但我试了一下)
…还有我的系统中的一些其他function,我可以在保持代码断开的情况下将其删除。
但在所有这些情况下TypeError: WHATEVER.catch is not a function
。
我应该在哪里捕捉这个MongoError
? (再次,我知道如何防止它)
你得到这个的原因是由于定义了重复的索引。
你应该只有这些行中的一个。
TestSchema.index({'num': 1}, { sparse: true }) TestSchema.index({'num': 1}, { sparse: false })
Unhandled promise
实际上来自与createIndex
相关的node-mongodb-native中的拒绝。 这不是暴露在mongoose为您发现错误。
可能的逻辑推理就是你的模式定义不应该有错误。 这是在开发过程中可能/应该容易被捕获的事情,不会在以后重复。
查看了一下,find了这篇文章 ,对这个问题的一个可能的答案可能是添加这一行:
process.on('unhandledRejection', function(error) { // do something with this error })
这样做意味着这个警告消失了:
(node:26795) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
但我实际上并不知道这会阻止Node.js进程退出。