gpt4 book ai didi

node.js - 我应该在哪里捕获这个 Promise MongoError?

转载 作者:可可西里 更新时间:2023-11-01 09:48:10 27 4
gpt4 key购买 nike

我升级了我的 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.

修复底层错误很容易,但我不知道我应该在哪里捕获它,这样 future 版本的 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() 函数上尝试了两种错误处理,但是当我运行它时输出的是

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('测试', TestSchema)
  • 甚至 require('mongoose')(这感觉很蠢,但我试过了)

...还有我系统中的一些其他功能,我能够在保持代码损坏的同时删除这些功能。

但在所有这些情况下 TypeError: WHATEVER.catch is not a function

我应该在哪里捕获这个 MongoError? (同样,我知道如何预防)

最佳答案

你得到这个的原因是因为定义了重复的索引。

你应该只有其中一行。

TestSchema.index({'num': 1}, { sparse: true })
TestSchema.index({'num': 1}, { sparse: false })

Unhandled promise 实际上来自 node-mongodb-native 中的拒绝与 createIndex 相关。这不会在 mongoose 中公开供您捕获错误。

可能的逻辑推理很简单,您的模式定义中永远不应该有错误。这是在开发过程中可以/应该很容易发现的东西,以后不会再重复了。

关于node.js - 我应该在哪里捕获这个 Promise MongoError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47244538/

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