Mongoose不在nodejs中获取数据



在使用mongoshell时没有数据被获取,它工作得很好

server.js文件
const express = require('express')
const app = express()
const cors = require('cors')
const mongoose = require('mongoose')
const topicRoute = require('./routes/topicRoute')
app.use(cors())
app.use(express.json())
const dbUri = "mongodb+srv://rohan:password@db_name.qg229.mongodb.net/db_name"
mongoose.connect(dbUri)
app.use("/",topicRoute)
app.listen(3001,function(){
console.log("Server started")
})

routes/topicRoute.js文件,这里没有捕获错误&返回对象

const express = require('express')
const router = express.Router()
const Topic = require('../models/topicModel')
router.route("/topics").get((req,res)=>{
Topic.find().then(fetchedTopics => res.json(fetchedTopics))
})
module.exports = router

模型/topicModel.js文件

const mongoose = require('mongoose')
const topicSchema = {
topic_id: String,
topic_name: String,
topic_description: String,
}
const Topic = mongoose.model('topics',topicSchema)
module.exports = Topic

尝试使用以下代码进行数据库连接

// database connection 
const { MongoClient, Collection } = require('mongodb');

const url = 'mongodb://localhost:27017' const database = 'ecom'     // database name define here const collectionName = 'reviews';   //database collection define here const client = new MongoClient(url);

async function getData(){
let result =await client.connect();
let db = result.db(database)
let collection = db.collection(collectionName)
let response = await collection.find({}).toArray()
console.log(response); }

getData();

最新更新