如何使用Mongoose连接Mongo-Atlas数据库?

时间:2019-08-02 00:45:09

标签: mongodb-atlas

我正在按照本教程设置mongo atlas数据库。

https://developerhandbook.com/mongodb/connect-mongo-atlas-mongoose/

但是在建立连接时,出现类似错误

(node:60566) UnhandledPromiseRejectionWarning: MongoError: user is not allowed to do action [find] on [admin.sample_airbnb]
    at queryCallback (/Users/jay.lin/dev/graphql-playlist/server/node_modules/mongodb-core/lib/cursor.js:223:25)
    at /Users/jay.lin/dev/graphql-playlist/server/node_modules/mongodb-core/lib/connection/pool.js:541:18
    at process._tickCallback (internal/process/next_tick.js:61:11)
(node:60566) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:60566) [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.

似乎Atlas db默认使用“ admin”集合,如何将其更改为“ sample_airbnb”集合?

    const connector = mongoose.connect(
        'mongodb+srv://test:<password>@cluster0-ppeaz.mongodb.net/a?retryWrites=true&w=majority'
    )
    .then(() => {
        // connector.useDb('sample_airbnb?');
        const Listing = mongoose.model(
            'listingsAndReviews',
            new mongoose.Schema({
                name: String,
                summary: String,
            }),
            'sample_airbnb'
        );
        Listing.findOne({}).then((r) => {
            console.log(r);
        })
    })

1 个答案:

答案 0 :(得分:0)

(节点:60566)您需要添加“管理员权限”才能查询数据库。这将在“安全”选项卡下,然后在“数据库访问”下。 “添加新用户”按钮(然后在您的连接字符串中使用)。

“。mongodb.net/a?”需要为“ .mongodb.net / sample_airbnb?”

(节点:60566)使用try catch例如

const connector = mongoose.connect(
        'mongodb+srv://test:<password>@cluster0-ppeaz.mongodb.net/sample_airbnb?retryWrites=true&w=majority'
    )
    .then(() => {
        // connector.useDb('sample_airbnb?');
      const Listing = mongoose.model(
          'listingsAndReviews',
           new mongoose.Schema({
                name: String,
                summary: String,
           }),
          'sample_airbnb'
        );
    try {
        const listings = await Listing.findOne({});
        res.json(listings);
      } catch (err) {
        res.json({ message: err });
      }
    });
});