javascript - 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() 函数运行之前放置的所有内容,但是当涉及到它们时,应用程序只是停留在那里,不做任何其他事情。
解决方案
我在本地快速路由器上试过,我相信问题出在它身上,试试这个对我有用:
// 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 })
})
})
推荐阅读
- javascript - 从nodejs插入日期值到mongodb
- c# - 当用户在浏览器中单击返回时,C# 防止插入数据库
- java - ServerBeginResponse 和 GotResponseHeaders 之间的延迟
- php - 为什么日文输入的修剪功能无法正常工作?
- reactjs - 如何将 useEffect 重构为 onlick 函数
- r - 如何在 R 中写出这个总和?
- javascript - 为什么我的返回 row[0] === userId.matches(userId); 什么都不显示?
- wso2 - 使用 Oauth2 和 SOAP 创建服务提供者
- discord.js - 使用 .then() 向 1 个频道发送 2 条消息
- python - 如何在 Python 中的某个起点将某些十六进制值放入数组中