javascript - TypeError:Room.findOne 不是函数

我刚刚开始学习如何通过使用我尝试将数据添加到 mongoDB 并使用 .findOne 函数来构建一个 database,但是我收到了这个错误。 findOne 是 MongoDB 中的函数吗?

我的目标是尝试构建一个完整的堆栈移动应用程序并将 mongoDB 用于 database。前端颤抖。我正在尝试使用 socket.io 将数据从颤振发送到 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};

老实说,我无法弄清楚为什么会遇到此错误。也许,我只需要第二只眼睛来帮助我。

任何人都可以帮助解决这个错误吗?请提前谢谢您!

回答1

您的错误位于此处:

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 集合/mongoose 模型中的一个函数。这意味着 const Room 必须是您调用 Room.findOne() 的集合

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

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

这是因为根据 https://mongoosejs.com/docs/models.html,从 Room.js 导出的是 {gameModel, roomSchema} 而不仅仅是您的模型,您应该调用该函数。因此,没有 findOne() 功能的 const Room = {gameModel, roomSchema}

修理:

当您像这样导入模式和模型时,尝试对象解构模式和模型。

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

相似文章

python - 如何使对象出现在预期的库存中?

对于此代码,它有多个房间,并且在每个房间中,当您使用动作外观时,您可以将某些物品和可抓取物品放入人员的库存中。但是,当我运行代码并使用外观操作时,它不会将对象放入库存中,而是将其留空。其他功能,例如向...

python - 房间探索;从字典中收集项目的问题

我正在使用Python创建一个房间探索游戏,但在收集物品和满足获胜条件时遇到问题(收集所有物品以“获胜”,如果没有收集到所有物品,则失败)。房间移动、帮助和退出功能,但我不知道从哪里开始。我为“get...

最新文章