mongoose 无法从mongoDB访问数据?

n7taea2i  于 2023-08-06  发布在  Go
关注(0)|答案(3)|浏览(93)

我遵循了一个教程,通过mongoose连接到mongoDB,但由于某种原因console.log(data)没有显示任何内容。

const mongoose = require('mongoose');
const mongoURI = 'mongodb+srv://gofood:xxxxxxxxx@cluster0.bgpaa3e.mongodb.net/?retryWrites=true&w=majority'

process.on('uncaughtException', err => {
  console.log('UNCAUGHT EXCEPTION! 💥 Shutting down...');
  console.log(err.name, err.message);
  process.exit(1);
});

async function called(){
  console.log('Connection successful!');
  const fetched_data = await mongoose.connection.db.collection("foodCategory");
  console.log('reaching here?????')
  fetched_data.find({}).toArray(function(err, data){
    if(err) console.log(err);
    else console.log(data);})
};

const mongoDB = async () => {
  await mongoose
    .connect(mongoURI, {
      useNewUrlParser: true
    })
    .then(() => called())
}

module.exports = mongoDB;

字符串
输出:-

[nodemon] starting `node .\index.js`
Example app listening on port 5000
Connection successful!
reaching here?????


在教程中,数据立即出现。有什么我没做的吗?

zbwhf8kr

zbwhf8kr1#

尝试await直到找到所有数据

async function called(){
  console.log('Connection successful!');
  const fetched_data = await mongoose.connection.db.collection("foodCategory");
  console.log('reaching here?????')
  await fetched_data.find({}).toArray(function(err, data){
    if(err) console.log(err);
    else console.log(data);})
};

字符串

cfh9epnr

cfh9epnr2#

你可以像这样修改called()函数:

async function called() {
console.log('Connection successful!');
const FoodCategory = mongoose.model('FoodCategory', new mongoose.Schema({}));
const data = await FoodCategory.find().exec();
console.log(data);
}

字符串
可能是工作吧!!

p4tfgftt

p4tfgftt3#

我就是这么解决的。我想知道在我的函数中,我提供了我的集合名称,而不是数据库名称。后来我发现在mongoDB的url中你必须提到数据库名称
旧url
第一个月
新url
const mongoURI = 'mongodb+srv://gofood:xxxxxx@cluster0.bgpaa3e.mongodb.net/**gofoodmern**?retryWrites=true&w=majority'

相关问题