我升级了我的猫鼬,所以当然我开始得到这些:
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.
很容易修复潜在的错误,但我 没有线索 我应该抓住它以便将来的版本如果他们遇到类似的事情,他们不会突然崩溃。我生成了一个产生错误的代码的最小版本。这是一个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()
函数上尝试了两种错误处理,但运行时输出的是
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(...)
添加到字面上的所有其他功能:
mongoose.Schema(...)
TestSchema.index({'num': 1}, { sparse: true })
mongoose.model('Test', TestSchema)
require('mongoose')
(这感觉很愚蠢,但我试过了)...还有我系统中的一些其他功能,我可以在保持代码损坏的情况下删除。
但在所有这些情况下TypeError: WHATEVER.catch is not a function
。
我应该在哪里抓住这个MongoError
? (再次,我知道如何防止它)
答案 0 :(得分:1)
你得到这个的原因是由于定义了重复的索引。
你应该只有其中一行。
TestSchema.index({'num': 1}, { sparse: true })
TestSchema.index({'num': 1}, { sparse: false })
Unhandled promise
实际上来自与createIndex
相关的node-mongodb-native拒绝。这不会暴露在mongoose中,因为你可以捕获错误。
可能的逻辑推理只是你的模式定义中永远不会有错误。这是在开发过程中可以/应该很容易捕获的东西,不会在以后重复。
答案 1 :(得分:0)
在再看一遍并找到this article之后,这个问题的一个可能答案可能是添加这一行:
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进程退出。