我正在创建MERN
堆栈应用程序,试图将我的应用程序与MongoDb
数据库连接。我正在使用Mongoose
库与`MongoDb连接。我在下面收到错误消息:< / p>
错误
TypeError:回调不是函数 ['server]位于$ initialConnection。$ initialConnection.then(H:\ React projects \ MyBlog \ node_modules \ mongoose \ lib \ connection.js:744:13) ['server]在process._tickCallback(internal / process / next_tick.js:68:7)
以下是我的代码:
server.js
const express = require('express');
const path = require('path');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(require('./routes/saveData.js'));
const port = process.env.PORT || 5000;
app.listen(port,() => {
console.log(`Server is running on ${port}.`);
});
saveData.js
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const blogs = require('../models/blogPost');
const mongoose = require('mongoose');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended: true}));
const dburl = 'mongodb+srv://example:example@cluster1-5wp.mongodb.net/ExpDb?retryWrites=true'
router.post('/save',(req,res) => {
const data = {
title: req.body.title,
detail: req.body.detail
}
const newBlog = new blogs(data);
mongoose.connect(dburl, {useNewUrlParser: true,useUnifiedTopology:true}).then((resp) =>{
resp.send("Connected");
console.log("connected");
}).catch((err) => {
console.log("database error: ",err);
});
});
module.exports = router;
下面是猫鼬模式: blogPost.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BlogPostSchema = new Schema({
title:String,
body:String,
date:{
type:String,
dafault:Date.now()
}
});
const BlogPost = mongoose.model('BlogPost',BlogPostSchema);
module.exports = BlogPost;
请让我知道我做错了。任何帮助将不胜感激。
谢谢
答案 0 :(得分:1)
猫鼬返回的承诺值为resp
。具有.send
方法的服务器响应对象是res
。请尝试以下:
router.post('/save', (req, res) => {
...
mongoose.connect(dburl, {useNewUrlParser: true, useUnifiedTopology:true}).then((resp) =>{
// res not resp
res.send("Connected");
console.log("connected");
})
答案 1 :(得分:1)
文档中的语法
mongoose.connect(uri, options).then(
() => { /** ready to use. The `mongoose.connect()` promise resolves to mongoose instance. */ },
err => { /** handle initial connection error */ }
);
代码
router.post('/save',(req,res) => {
mongoose.connect(dburl, {useNewUrlParser: true,useUnifiedTopology:true})
.then(() =>{
res.send("Connected");
console.log("connected");
},(err)=> console.log("database error: ",err);)
});
答案 2 :(得分:0)
猫鼬连接没有回调
mongoose.connect(dburl, {useNewUrlParser: true},{useUnifiedTopology:true});
这应该有效。然后要更新,您应该在模型对象上使用猫鼬保存方法。
BlogPost.save();