TypeError: Room.findOne is not a function

TypeError: Room.findOne is not a function

我刚开始学习如何使用 我正在尝试将数据添加到 mongoDB 并使用 .findOne 函数 ,但出现此错误。 findOne 是 MongoDB 中的函数吗?

我的目标是尝试构建一个完整的堆栈移动应用程序并使用 mongoDB 作为数据库。前端是颤动的。我正在尝试使用 socket.io.

将数据从 flutter 发送到 mongoDB

如果我只需要将数据保存到 MongoDB,您可能会问自己为什么要使用 socket.io。好吧,应用程序构建是一个游戏,多个用户可以加入一个房间并相互互动。

这里是用来构建后端的版本"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 这是我的主文件

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:1111@cluster0.tllj9.mongodb.net/?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};

老实说,我不明白为什么会遇到这个错误。也许,我只是需要第二只眼睛来帮助我。

谁能帮忙解决这个错误?请提前谢谢你!

您的错误位于此处:

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;
            }

解释:

现在,findOne 是 mongoDB collection/mongoose 模型中的一个函数。这意味着 const Room 必须是您调用 Room.findOne()

的集合

但是,根据您的 index.js 文件,当您调用 Room 时,您并没有获取 mongodb collection/mongoose 模型。

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

这是因为从 Room.js 导出的是 {gameModel, roomSchema} 而不仅仅是您的模型,根据 Mongoose documentation,您应该从中调用函数。因此,const Room = {gameModel, roomSchema},没有findOne()功能

修复:

像这样导入模式和模型时尝试对象 de-structuring。

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