Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

235
Visualizações
Express + MongoDB

I try to connect an application to mongoDB with express, for the moment i have no problem with the collection users, it works perfectly but it doesn't work for my second collection, when i try to get all data of my second collection, express return me a empty array.

// Import dependencies
const mongoose = require('mongoose');
const express = require('express');
const router = express.Router();

// MongoDB URL from the docker-compose file
const dbHost = 'mongodb://database/mybase';

// Connect to data
mongoose.connect(dbHost);

// create mongoose schema
const userSchema = new mongoose.Schema({
    mail: String,
    mdp: String,
    firstname: String,
    participants: Number
});

// create mongoose schema
const roomSchema = new mongoose.Schema({
    roomId: String,
});

// create mongoose model
const User = mongoose.model('User', userSchema);
const Room = mongoose.model('Room', roomSchema);

/* GET api listing. */
router.get('/', function(req, res) {
    res.send('api works');
});

/* GET all users. */
router.get('/users', function(req, res) {
    User.find({}, function (err, users) {
        if (err) {
            res.status(500).send(error)
        }
        res.status(200).json(users);
    });
});

/* GET all rooms. */
router.get('/room', function(req, res) {
    Room.find({}, function (err, room) {
        if (err) {
            res.status(500).send(error)
        }
        res.status(200).json(room);
    });
});

module.exports = router;

In my mongo data are stored like this :

> db.users.find()
{ "_id" : ObjectId("5903a7ee0e999a5054cc402b"), "mail" : "mail@google.com", "mdp" : "toto", "firstname" : "firstname", "participants" : 100 }
{ "_id" : ObjectId("5903ae7952163fd952970ed5"), "mail" : "mail2@google.com", "mdp" : "toto", "firstname" : "firstname", "participants" : 50 }

> db.room.find()
{ "_id" : ObjectId("59043f280d062a4959b69315"), "roomId" : "6733454" }

I search for a long time but to be honest, i don't know why it doesn't work, i also try to put users data into room data and to copy/paste user schema into room schema, but it doesn't work also.

If i put the User model object in router.get room, it works, i get users data, so for me it's not a problem of route.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

By default, Mongoose applies a function (utils.toCollectionName()) to the name of a model to determine the collection name that Mongoose will use for that model. For a model called Room, that collection name will be rooms.

However, your collection is called room (singular), so there's a mismatch there.

To fix this, you can explicitly specify which collection should be used using the collection schema option:

const roomSchema = new mongoose.Schema({
  roomId: String,
}, {
  collection : 'room'
});
over 4 years ago · Santiago Trujillo Relatório

0

The problem is that the name of your collection is room, as in singular. The correct name for the collection is rooms, plural.

Mongoose infers from the model name Room that there should be a collection named rooms in the database. If there isn't, it just fails silently and returns an empty array.

If you simply change the name of your collection in the database from room to rooms, your code will work.

You can do so with the renameCollection command.

over 4 years ago · Santiago Trujillo Relatório

0

Thanks you guys, it was just that and it was in front of me all this times...

It works perfect with collection rooms and not room

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda