【问题标题】:mongoose.connect(uri, ConnectOptions) does not recognize useNewUrlParser and other optionsmongoose.connect(uri, ConnectOptions) 不识别 useNewUrlParser 和其他选项
【发布时间】:2021-12-28 16:09:27
【问题描述】:

我的 GitHub 仓库:https://github.com/safiullah7/legan

分支:redux

我正在关注本教程:https://tomanagle.medium.com/build-a-rest-api-with-node-js-typescript-mongodb-b6c898d70d61 而且我无法连接到我的 mongodb。 这是我尝试与 mongodb 连接的代码文件:

import config from "config";
import log from "../logger";

function connect() {
  const dbUri = config.get("dbUri") as string;

  return mongoose
    .connect(dbUri, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
    .then(() => {
      log.info("Database connected");
    })
    .catch((error) => {
      log.error("db error", error);
      process.exit(1);
    });
}

export default connect;

编译器给出以下错误:

No overload matches this call.
  Overload 1 of 3, '(uri: string, callback: CallbackWithoutResult): void', gave the following error.
    Argument of type '{ useNewUrlParser: boolean; useUnifiedTopology: boolean; }' is not assignable to parameter of type 'CallbackWithoutResult'.
      Object literal may only specify known properties, and 'useNewUrlParser' does not exist in type 'CallbackWithoutResult'.
  Overload 2 of 3, '(uri: string, options?: ConnectOptions | undefined): Promise<typeof import("mongoose")>', gave the following error.
    Argument of type '{ useNewUrlParser: boolean; useUnifiedTopology: boolean; }' is not assignable to parameter of type 'ConnectOptions'.
      Object literal may only specify known properties, and 'useNewUrlParser' does not exist in type 'ConnectOptions'.

我是 typescript 和 node/mongoos 的新手。非常感谢您的帮助。

【问题讨论】:

标签: node.js typescript mongodb mongoose


【解决方案1】:

mongoose 的新版本(我写这篇文章时的最新版本是6.0.2)对于connect() 函数有以下类型定义。

/** Opens Mongoose's default connection to MongoDB, see [connections docs](https://mongoosejs.com/docs/connections.html) */
export function connect(uri: string, options: ConnectOptions, callback: CallbackWithoutResult): void;
export function connect(uri: string, callback: CallbackWithoutResult): void;
export function connect(uri: string, options?: ConnectOptions): Promise<Mongoose>;

您传递给connect() 函数的options object

{
  useNewUrlParser: true,
  useUnifiedTopology: true,
}

因此,它的类型应该是ConnectOptions

ConnectOptions 的当前定义如下:

interface ConnectOptions extends mongodb.MongoClientOptions {
  /** Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. */
  bufferCommands?: boolean;
  /** The name of the database you want to use. If not provided, Mongoose uses the database name from connection string. */
  dbName?: string;
  /** username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. */
  user?: string;
  /** password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. */
  pass?: string;
  /** Set to false to disable automatic index creation for all models associated with this connection. */
  autoIndex?: boolean;
  /** Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. */
  autoCreate?: boolean;
}

查看connectConnectOptions的新定义,我们可以看到ConnectOptions内部没有useNewUrlParseruseUnifiedTopology的定义。这就是我们得到这样一个错误的原因。您可以删除选项useNewUrlParser: true,useUnifiedTopology: true,,您的代码应该能够连接到您的MongoDB。如果您想将一些选项传递给connect() 函数,那么它们应该遵循ConnectOptions 的新类型定义。

【讨论】:

  • 很高兴您展示了自己如何正确使用该功能的方式。也许您可以添加到您的答案中,根据文档,这些标志现在默认设置,因此不再可以通过客户端选项使用。
【解决方案2】:

您可以将 mongoose.connect 函数更改为:

mongoose.connect(dbUri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
} as ConnectOptions)

这是最简单的方法

【讨论】:

  • 我们必须从哪里导入 ConnectOptions?
  • 进口猫鼬,{ ConnectOptions } from 'mongoose';
【解决方案3】:

更新:澄清此答案作为未来读者的参考。

如果您使用的是 Mongoose v6+,则此答案适用。

其他答案解释了如何扩展 typescript 以接受 useNewUrlParser 和其他选项,这将解决原始问题。

但是,根据 Mongoose 文档,如果您使用的是 Mongoose v6+,则不再需要这些选项,因为它们已作为默认值包含在内。

根据 Mongoose 迁移指南到版本 6:

useNewUrlParser、useUnifiedTopology、useFindAndModify 和 useCreateIndex 不再是受支持的选项。猫鼬 6 总是 表现得好像 useNewUrlParser、useUnifiedTopology 和 useCreateIndex 为真,而 useFindAndModify 为假。请删除这些选项 来自您的代码。

https://mongoosejs.com/docs/migrating_to_6.html#no-more-deprecation-warning-options

因此,不再需要包含这些选项。我想这就是为什么它们不再包含在 ConnectOptions 类型中的原因。

如果您使用的是旧版本的 Mongoose,请参阅其他答案以了解如何扩展 ConnectOptions 类型以允许这些选项。

【讨论】:

  • 这没有提供问题的答案。一旦你有足够的reputation,你就可以comment on any post;相反,provide answers that don't require clarification from the asker。 - From Review
  • 这才是真正的答案。旧版本的 mongo 文档促进了 useNewUrlParser 等的使用,因此这解释了用户看到的错误。不知道为什么你对这个@mbuechmann 有问题
  • 我在学习另一个 Tom Nagal 教程 link 时也遇到了与 @SU7 相同的问题。汤姆说两者都运行yarn add mongoose。这获得了最新版本(现在 6+),而教程代码似乎是用 5+ 编写的。这种 mongoose 版本不匹配会导致编译错误。修复方法是删除@Nickolai 和@Hoang 指示的选项。您可以在 package.json 中将您的 mongoose 版本固定为 5+,但删除选项对象是一个有效的答案。
【解决方案4】:

到目前为止,只是在等待来自 mongoose 的新更新,同时有一个解决方法可能会有所帮助

import { ConnectionOptions, connect } from "mongoose"

type ConnectionOptionsExtend = {
  useNewUrlParser: boolean
  useUnifiedTopology: boolean
}

const options: ConnectionOptions & ConnectionOptionsExtend = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  authSource: "admin",
  useCreateIndex: true,
  useFindAndModify: false,
  user,
  pass
}

await connect(uri, options)

【讨论】:

    猜你喜欢
    • 2021-03-17
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    • 2019-10-22
    • 1970-01-01
    相关资源
    最近更新 更多