Home > other >  TypeError: Room.findOne is not a function
TypeError: Room.findOne is not a function

Time:05-20

I just learning how to build a database by using Im trying to add data to mongoDB and using the .findOne function, but I'm getting this error. is findOne a function in MongoDB?

My Goal is I trying to build a full stack mobile application and using mongoDB for database. FrontEnd is flutter. I'm trying to send data from flutter to mongoDB using socket.io.

You might ask yourself I'm using socket.io if I just need to save data to MongoDB. Well, The application building is game where multiple users can Join a room and interact with each other.

Here is the versions that using to build these backend "mongoose": "^6.3.3", "socket.io": "^2.3.0"

TypeError: Room.findOne is not a function
    at Socket.<anonymous> (/Users/Paul/Documents/server/Index.js:27:45)
    at Socket.emit (node:events:390:28)
    at /Users/Paul/Documents/server/node_modules/socket.io/lib/socket.js:528:12
    at processTicksAndRejections (node:internal/process/task_queues:78:11)

Index.js Here is my main file

const express = require("express");
var http = require("http")
const app = express();
const port = process.env.PORT || 3000;
var server = http.createServer(app);
const mongoose = require("mongoose");
const Room = require('./models/Room');
//adding socket IO and passing the variable server to it.
var io = require("socket.io")(server);

//middleware
app.use(express.json());

//connecting to MongoDB
const DB = 'mongodb srv://user:[email protected]/?retryWrites=true&w=majority';

mongoose.connect(DB).then(() => {
    console.log('Connection Successful!');
}).catch((e) =>{
    console.log(e);
})

io.on('connection', (socket) => {
    console.log('connected!');
    socket.on('create-game', async({nickname, name, numRounds, occupancy}) => {
        try {
            const existingRoom = await Room.findOne({name});
            if(existingRoom){
                socket.emit('notCorrectGame', 'Room with that name already exists!');
                return;
            }
            let room = new Room();
            const word = getWord();
            room.word = word;
            room.roomName = roomName;
            room.occupnacy = occupnacy;
            room.numRounds = numRounds;

            let player = {
                socketID: socket.id,
                nickname,
                isPartyLeader: true,
            }
            room.players.push(player);
            room = await room.save();
            socket.join(room);
            io.to(roomName).emit('updateRoom', room);

        } catch (error) {
            console.log(error);
        }
    })
})

server.listen(port, "0.0.0.0", () => {
    console.log('Server started and running on port '   port);
})

Player.js

const mongoose = require('mongoose');

const PlayerSchema = new mongoose.Schema({
    nickname: {
        type: String,
        trim: true,
    },
    socketID: {
        type: String,
    },
    isPartyLeader: {
        type: Boolean,
        default: false,
    },
    points: {
        type: Number,
        default: 0,
    }
})

const playermodel = mongoose.model('Player', PlayerSchema);
module.exports = {playermodel, PlayerSchema}

Room.js

const mongoose = require("mongoose");
const { PlayerSchema } = require("./Player");

var roomSchema = new mongoose.Schema({
  word: {
    required: true,
    type: String,
  },
  name: {
    required: true,
    type: String,
    unique: true,
    trim: true,
  },
  occupancy: {
    required: true,
    type: Number,
    default: 4
  },
  maxRounds: {
    required: true,
    type: Number,
  },
  currentRound: {
    required: true,
    type: Number,
    default: 1,
  },
  players: [PlayerSchema],
  isJoin: {
    type: Boolean,
    default: true,
  },
  turn: PlayerSchema,
  turnIndex: {
    type: Number,
    default: 0
  }
});

const gameModel = new mongoose.model('Room', roomSchema);
module.exports = {gameModel, roomSchema};

I honestly cant figure out why I encountering this error. Maybe, I just need a second eyes to help me out.

Can anyone help with this error? Please and Thank you in advance!

CodePudding user response:

Your error is located here:

io.on('connection', (socket) => {
    console.log('connected!');
    socket.on('create-game', async({nickname, name, numRounds, occupancy}) => {
        try {
            //error is here
            const existingRoom = await Room.findOne({name});
            if(existingRoom){
                socket.emit('notCorrectGame', 'Room with that name already exists!');
                return;
            }

Explanation:

Now, findOne is a function in mongoDB collection/mongoose model. This means const Room must be a collection for you to call Room.findOne()

However, according your index.js file, when you call Room, you aren't grabbing the mongodb collection/mongoose model.

const Room = require('./models/Room');

This is because the export from Room.js is {gameModel, roomSchema} and not just your model, which is what you should be calling the function off of, according to Mongoose documentation. Therefore, const Room = {gameModel, roomSchema}, which has no findOne() function

To fix:

Try object de-structuring the schema and model when you import it like so.

const {gameModel: Room, roomSchema} = require('./models/Room')
  • Related