【问题标题】:What should I do to connect mongoose 5.8 with mongodb?mongoose 5.8 和 mongodb 连接应该怎么做?
【发布时间】:2020-04-14 01:44:40
【问题描述】:

我正在使用猫鼬。 5.8.2 并遵循该人在 v3.5 上运行 mongoose 的教程。我知道有一些变化,比如 useNewUrlParser 已被弃用,而是我们使用 useUnifiedTopology 但问题是每当我使用 useUnifiedTopology 时,我都会收到它已被弃用的错误。请看下面,让我知道我做错了什么

const mongoose = require('mongoose')

mongoose.createConnection('mongodb://127.0.0.1:27017/task-manager-api', {
    useUnifiedToplogy: true,
    useCreateIndex: true

});

const User = mongoose.model('User', {
    name: {
        type: String
    },
    age: {
        type: Number
    }
})

const me = new User({
    name: 'Lallan',
    age: '27'
})

me.save().then(() => {
    console.log('Done')
}).catch((error) => {
    console.log('error', error)
})

以下是错误,我无法将 mongoose 与 mongodb 连接

the options [useUnifiedToplogy] is not supported
(node:6573) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:6573) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.

mongoose 和 mongodb 连接应该怎么做?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    最默认的连接是{ useNewUrlParser: true }。您可以使用createConnection()(用于多个池)以及connect()(单个池)。

    来自MDN 的一个基本示例将是:

    //Import the mongoose module
    var mongoose = require('mongoose');
    
    //Set up default mongoose connection
    var mongoDB = 'mongodb://127.0.0.1/my_database';
    mongoose.connect(mongoDB, { useNewUrlParser: true });
    
    //Get the default connection
    var db = mongoose.connection;
    
    //Bind connection to error event (to get notification of connection errors)
    db.on('error', console.error.bind(console, 'MongoDB connection error:'));
    

    还有,

    如果您需要创建其他连接,您可以使用 mongoose.createConnection()。这采用相同形式的数据库 URI (带有主机、数据库、端口、选项等)作为 connect() 并返回一个 连接对象。

    喜欢,

    const db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts);
    

    【讨论】:

    • 仍然显示此错误 (node:7030) DeprecationWarning: 当前的服务器发现和监控引擎已被弃用,并将在未来的版本中删除。要使用新的服务器发现和监控引擎,请将选项 { useUnifiedTopology: true } 传递给 MongoClient 构造函数。
    • 很抱歉这么晚的评论,只需添加 useUnifiedToplogy: true 选项。它不会再显示警告。
    【解决方案2】:

    也许可以试试这种方式,

    const mongoose = require('mongoose');
    let db_uri = "'mongodb://localhost:27017/mydb"
    
    mongoose.connect(db_uri, {
      useNewUrlParser: true,
      useUnifiedTopology : true
    });
    mongoose.set('useCreateIndex', true);
    mongoose.set('useFindAndModify', false);
    

    【讨论】:

      猜你喜欢
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      • 2012-10-24
      • 1970-01-01
      • 2015-07-10
      • 2017-07-13
      • 1970-01-01
      • 2021-08-13
      相关资源
      最近更新 更多