mongodb with nodejs在向mongodb添加文档时返回空错误



我在邮差中点击发送大约5秒后得到这个错误:

{
"message": {}
}

错误发生的地方:

router.post('/', async (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
});
try {
const savedPost = await post.save();
res.json(savedPost);
} catch (err) {
res.json({message: err}); // here
}
});

我在console.log中连接到DB (mongo是由docker-compose运行的)

mongodb:
image: mongo
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: admin
MONGO_INITDB_DATABASE: test_db
ports:
- 27017:27017

DB_CONNECTION = mongodb://admin: admin@mongodb: 27017/test_db

mongoose.connect(
process.env.DB_CONNECTION, 
{ 
useNewUrlParser: true,
useUnifiedTopology: true
},
() => console.log('connected to DB!!!') // call back
);

Schema:

const mongoose = require('mongoose');

// describe how the data looks
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)

然而,当我更新DB_connection为:DB_CONNECTION=mongodb://admin:admin@mongodb:27017(删除/test_db)问题消失了,我和完美地添加文档到mongodb(但不是在test_db)

有人知道问题在哪里吗?非常感谢!!

你总是可以使用回调:

post.save(function(err, obj) {
if (err)
res.send(err);
res.json({ message: 'created!', data: obj });
});

相关内容

  • 没有找到相关文章

最新更新