【问题标题】:Application not sending or receiving data from mongodb应用程序未从 mongodb 发送或接收数据
【发布时间】:2020-06-30 18:52:29
【问题描述】:

我正在创建一个简单的练习 restful 应用程序,并且我正在尝试测试我的路线。

我的路线如下所示:

router.get('/', (req, res) => {
    const posts = Post.find();
    res.json(posts);
});

router.post('/', (req, res) => {
    const post = new Post({
        title: req.body.title,
        description: req.body.description
    });

    post.save()
    .then(data => {
        res.json(data);
    })
    .catch(err => {
        res.json({ message: err});
        console.log(err);
    })
});

这里是我建立 mongodb 连接以及带有 db 连接的 .env 文件的地方:

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
require('dotenv/config');

app.use(bodyParser.json());

//Import Routes
const postRoute = require("./routes/posts");

app.use('/posts', postRoute);

app.get('/', (req, res) => {
    res.send("home");
});

mongoose.connect(
    process.env.DB_CONNECTION, 
{   useNewUrlParser: true, //depriciated without this
    useUnifiedTopology: true}, //depriciated without this
() => console.log('connected to db'));

app.listen(3000);

//env file:___________________________________________________________
DB_CONNECTION=mongodb+srv://user-0:<test>@cluster0.wb39f.mongodb.net/<test-db>?retryWrites=true&w=majority

当我向邮递员发送 get 请求时,我收到此错误:

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'NativeConnection'
    |     property 'base' -> object with constructor 'Mongoose'
    |     property 'connections' -> object with constructor 'Array'
    --- index 0 closes the circle
    at JSON.stringify (<anonymous>)
    at stringify (C:\Users\westo\Documents\code stuff\restful\node_modules\express\lib\response.js:1123:12)
    at ServerResponse.json (C:\Users\westo\Documents\code stuff\restful\node_modules\express\lib\response.js:260:14)
    at C:\Users\westo\Documents\code stuff\restful\routes\posts.js:7:9
    at Layer.handle [as handle_request] (C:\Users\westo\Documents\code stuff\restful\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\westo\Documents\code stuff\restful\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\westo\Documents\code stuff\restful\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\westo\Documents\code stuff\restful\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\westo\Documents\code stuff\restful\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\westo\Documents\code stuff\restful\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\westo\Documents\code stuff\restful\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\Users\westo\Documents\code stuff\restful\node_modules\express\lib\router\index.js:174:3)
    at router (C:\Users\westo\Documents\code stuff\restful\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (C:\Users\westo\Documents\code stuff\restful\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\westo\Documents\code stuff\restful\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\westo\Documents\code stuff\restful\node_modules\express\lib\router\index.js:284:7

当我发送发布请求时,我会收到一条超时消息:

POST http://localhost:3000/posts
Error: socket hang up
Request Headers
Content-Type: application/json
User-Agent: PostmanRuntime/7.26.1
Accept: */*
Postman-Token: 59a4d266-3607-4b7b-b952-a843e4e36192
Host: localhost:3000
Accept-Encoding: gzip, deflate, br
Connection: keep-alive

这里要求的是 Post Schema:

const mongoose = require('mongoose');

const PostSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    description:{
        type: String,
        required: true
    }/*,
    date:{
        type: Date,
        default: Date.now,
        required: false
    }*/
});

module.exports = mongoose.model('Posts', PostSchema);

我不确定我的代码或数据库有什么问题。根据我看到的所有教程,他们都设置并编写了他们的代码,基本上是我做的。我认为我的应用程序尝试连接到 mlab 的方式可能存在问题,但我不确定。

【问题讨论】:

  • 能否将已建立连接的文件添加到mongodb

标签: node.js rest mongoose


【解决方案1】:

如果您使用猫鼬,您能否提供文件,您在哪里指定 Post 方案?

我猜你会的

问题可能在于序列化您从猫鼬获得的 Promise。 尝试使用 async-await 或 .then() 来完成,就像你在 post 方法中所做的那样

【讨论】:

    【解决方案2】:

    数据库操作是asynchronous 操作。因此,我建议将async-await 用于您的路由控制器功能。

    例如:

    router.get('/', async (req, res) => {
        const posts = await Post.find({});
        res.json(posts);
    });
    
    router.post('/', async (req, res) => {
        try {
            const post = await Post.create({
                title: req.body.title,
                description: req.body.description
            });
            res.json(data);
        }
          catch(err) {
            res.json({ message: err});
            console.log(err);
        }
    });
    

    这至少应该解决从数据库推送/检索数据的问题。 一旦到位,就可以检查与 MongoDB 连接相关的问题。

    【讨论】:

    • 感谢您的建议。这似乎有助于解决发布请求时的套接字挂断问题。但是,尽管使用帖子 json 正确发回了响应,但它仍然没有在数据库中找到示例帖子或发布新帖子。
    • 用正确的猫鼬查询更新了我的答案。我为findcreate 功能调用了错误的方法
    • 在优化代码以满足适当的规范后仍然存在超时错误,所以这里肯定有一些额外的事情
    【解决方案3】:

    当你使用 find() 时,你必须传递一个对象作为参数来查找所有帖子,并且正文解析器必须是 app.use(bodyParser.urlencoded{ extended: true })

    【讨论】:

      猜你喜欢
      • 2012-12-09
      • 1970-01-01
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      相关资源
      最近更新 更多