【发布时间】:2022-01-15 10:41:52
【问题描述】:
我正在尝试使用 Apollo-Server-Express 中的 mongoose 连接到我的数据库。我在终端中创建了一个数据库。我读到'mongodb://localhost:27017/*db-name *' 是 mongoose.connect 作为第一个参数的默认 uri-string。
但是,console.log(mongoose.connection.readyState) 打印出 '2' - 连接。
我会期待'1',对吧?
查询时,服务器冻结,并抛出 ServerSelectionError。
我尝试在 mongoose.connect 语句之前加上 await (正如我在教程中看到的那样),但随后启动过程冻结了。
我缺少什么基本的东西吗?
任何帮助表示赞赏!
const { ApolloServer, gql } = require('apollo-server-express');
const express = require('express');
const mongoose = require('mongoose');
const main = async () => {
const app = express();
const server = new ApolloServer({
typeDefs,
resolvers,
introspection: true,
playground: true,
});
await server.start();
server.applyMiddleware({
app,
});
mongoose.connect('mongodb://localhost:27017/db-name', {
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log(mongoose.connection.readyState);
console.log('MongoDB connected!!');
app.listen(process.env.PORT || 4000, () => {
console.log(`???? Server ready at port ${process.env.PORT || 4000}`);
});
};
main();
【问题讨论】:
-
mongod 服务在运行吗?您可能需要打开终端并运行 mongod 命令。
-
你已经确认你有 mongodb 本身在运行?
标签: node.js mongodb express mongoose apollo