首页 > 解决方案 > Mongoose save() 和 find() 没有运行

问题描述

我正在尝试使用 mongoose 使用 mongodb 和 node.js 创建一个功能性页面,但是当我需要使用 mongoose 函数“mongoose.save()”或“mongoose.find()”时,它只是不运行,没有错误消息或类似的东西。

我去阿特拉斯看看有没有什么问题,一切似乎都很好

路由器相关代码

var express = require("express");
var router = express.Router();
const Post = require('../Models/Post');
//ALL POSTS ARE SHOWN
router.get("/", async (req, res) => {
    try{
    console.log('looking for all posts')
    const posts = await Post.find()
    res.json(posts)
    }catch(err){
        res.json({message: err})
    }
});
//A POST IS SEND
router.post('/', async (req, res)=>{
    const post = new Post({
        title: req.body.title,
        description: req.body.description
    })
    await post.save()
    .then(data=>{
        console.log(req.body)
        res.json(data)
    })
    .catch(err=>{
        res.json({ message: err })
    })
})

架构:

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

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

我在 save() 或 find() 函数运行之前放置的所有内容,但是当涉及到它们时,应用程序只是停留在那里,不做任何其他事情。

标签: javascriptnode.jsmongodbexpressmongoose

解决方案


我在本地快速路由器上试过,我相信问题出在它身上,试试这个对我有用:

// Create a constant of express
const app = express();

// Then instead of router use app.
app.post('/', async (req, res)=>{
    const post = new Post({
        title: req.body.title,
        description: req.body.description
    })
    await post.save()
    .then(data=>{
        console.log(req.body)
        res.json(data)
    })
    .catch(err=>{
        res.json({ message: err })
    })
})

推荐阅读