简体   繁体   中英

Cant connect to specific database and collection inside mongoDB Atlas Cluster

I am creating a MERN stack application and have chosen to use mongoose to communicate with MongoDB Atlas. But MongoDB Atlas uses clusters with databases inside which again has collections. I cant find any documentation for how to connect to a specific database and collection.

this is my current code:

File with the schema

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
  User: {
    fisrtname: String,
    lastname: String,
    email: String,
    password: String,
  },
  Todos: [
    {
      title: String,
      completed: Boolean,
      id: Schema.Types.ObjectId,
    },
  ],
});

module.exports = mongoose.model('User', userSchema, 'todosCollection');

Main server file

const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const dbConfig = require('./database/db');
const app = express();
const PORT = process.env.PORT || 8080;

// Connecting to MongoDB database
mongoose.Promise = global.Promise;
mongoose
  .connect(dbConfig.db, {
    useNewUrlParser: true,
  })
  .then(
    () => console.log('Database Sucsessfully connected!'),
    err => console.error('Could not connect to database: ' + err)
  );

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.use('/api/todos', require('./routes/api/todos'));

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

And the function who searches MongoDB. This is a snippet from another file but the rest is unimportant to the question.

const userSchema = require('../../database/models/User');

router.get('/', (req, res) => {
  userSchema.find((err, data) => {
    if (err) {
      res.staus(500).json({ msg: 'Did not found database data' });
    } else {
      res.json(data);
    }
  });
});

Once you have connected with your Atlas MongoDB cluster - you can treat it the same as any other MongoDB connection. See my answer on how to correctly connect to an Atlas cluster: https://stackoverflow.com/a/61480485/8322220 .

However, you also seem to be having an issue querying your data, but it is hard to help without the relevant code.

  • However, in your 3rd snippet, you are querying User - but I think your User schema is not correct.
  • I suggest that you separate Todos into its own Schema and export separately to User ie:

module.exports = mongoose.model('Todo', todoSchema)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM