Mongoose find()返回空数组

tkqqtvp1  于 2023-10-19  发布在  Go
关注(0)|答案(1)|浏览(113)

我有问题,试图得到我的数据下来从monogodb免费版。我有一个名为travel-app的应用程序和一个名为Trips的集合。

const mongoose = require('mongoose');

const tripEventSchema = new mongoose.Schema({
    name: String,
    description: String,
    startdate: Date,
    enddate: Date,
    cost: String,
    tripevent: String
  });
  
  const tripSchema = new mongoose.Schema({
    name: String,
    description: String,
    startdate: Date,
    enddate: Date,
    tripevents: [tripEventSchema]
  });
  
    const Trip = mongoose.model('Trips', tripSchema);

module.exports = Trip;

我的路线:

const express = require('express');
const Trip = require('../models/event'); // Update the path based on your directory structure

const router = express.Router();

router.get('/', async (req, res) => {
    try {
      const events = await Trip.find({});
      console.log('Events:', events); // Add this line
      res.json(events);
    } catch (err) {
      console.error('Error:', err); // Add this line
      res.status(500).json({ error: err.message });
    }
  });

module.exports = router;

我的服务器没有用户名和密码

const express = require('express');
const mongoose = require('mongoose');
const eventsRouter = require('./routes/events');

const app = express();

const dbURI = 'mongodb+srv://:@travel-app.jdkjive.mongodb.net/?retryWrites=true&w=majority';

mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log('Connected to the database');
  })
  .catch(err => {
    console.error('Error connecting to the database:', err);
  });

app.use(express.json());

app.use('/events', eventsRouter);

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

每当我路由到localhost:3000/events时,它会返回一个[],但我肯定有数据在我的收集中-直接从收集中复制,例如

{"_id":{"$oid":"64d904b9492a3c552b44f4d4"},"name":"Example Event","description":"This is an example event description.","startdate":"2023-08-15","enddate":"2023-08-18","tripevents":[{"name":"Trip 1","description":"This is the description of Trip 1.","tripevent":"Type A","startdate":"2023-08-15","enddate":"2023-08-16","cost":{"$numberInt":"500"}},{"name":"Trip 2","description":"This is the description of Trip 2.","tripevent":"Type B","startdate":"2023-08-17","enddate":"2023-08-18","cost":{"$numberInt":"750"}}]}

sz81bmfz

sz81bmfz1#

根据文档:
Mongoose会自动查找模型名称的小写形式的复数形式。因此,对于上面的示例,模型Tank用于数据库中的坦克集合。
在mongodb中,你的集合名为Trips。你需要把它命名为trips
也要改变这个:

const Trip = mongoose.model('Trips', tripSchema);

这是:

const Trip = mongoose.model('Trip', tripSchema);

相关问题