通过Thunderclient将数据插入MONGODB时出错

icomxhvb  于 2023-01-30  发布在  Go
关注(0)|答案(2)|浏览(108)

我是MERN Stack的新手,我尝试连接Mongo和Node,但在使用MongoDb Compass将数据插入数据库时遇到了这个问题
Index.js

const connectToMongo = require('./db');
const express = require('express')
connectToMongo();

const app = express()
const port = 3000

app.use(express.json())

//Available Routes
app.use('/api/auth', require('./routes/auth'))
app.use('/api/auth', require('./routes/notes'))

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

User.js

const mongoose = require('mongoose');
const { Schema } = mongoose;

const UserSchema = new Schema({
        name:{
            type: String,
            require: true
        },
        email:{
            type:String,
            require:true,
            unique: true
        },
        password:{
            type:String,
            require:true
        },
        timestamp:{
            type:Date,
            default:Date.now
        }
  });

  module.exports = mongoose.model('user', UserSchema)

auth.js

const express=require('express');
const User = require('../models/User');
const router=express.Router()

router.get('/', (req, res)=>{
        console.log(req.body)
        const user = User(req.body)
        user.save()
        res.send(req.body)
})

module.exports = router

db.js

const mongoose = require('mongoose')
const mongoURI = "mongodb://localhost:27017/"

const connectToMongo=()=>{
    mongoose.set("strictQuery", false);
    mongoose.connect(mongoURI,()=>{
        console.log("Connected to Mongo Successfully")
    })
}

module.exports = connectToMongo;

ThunderClient请求:

{
  "name":"pratik",
  "email":"pratik@mail.com",
  "password":"6626"
}

错误:常量错误=新MongooseError(消息);^
Mongoose 错误:操作users.insertOne()缓冲在10000ms后超时。(D:\Study\React\MERN\inotebook\backend\node_modules\mongoose\lib\drivers\node-mongodb-native\collection. js:175:23)在进程的listOnTimeout(节点:内部/计时器:564:17)上。进程计时器(节点:内部/计时器:507:7)
我猜问题是因为较新的版本,我试图阅读文档和StackOverFlow,但无法解决此错误我该怎么办

rks48beu

rks48beu1#

您得到这个错误是因为您实际上没有连接到mongo。您在db.js中丢失了async/await

const connectToMongo = async () => {
mongoose.set("strictQuery", false);
await mongoose.connect(mongoURI,
// you can add this opts
      { keepAlive: true,
        useNewUrlParser: true,
        useUnifiedTopology: true,
    })

console.log("Connected to Mongo Successfully")

}
稍后,当您调用user.save()时,它也应该是异步的:

async (req, res)=>{
    console.log(req.body)
    const user = User(req.body)
    await user.save()
    res.send(req.body)
5cg8jx4n

5cg8jx4n2#

Thanks Everyone解决方案非常简单,只需将您的本地主机更改为127.0.0.1:270

相关问题