简体   繁体   English

为什么我的 model 不能使用 mongoose 和 mongodb 保存?

[英]Why won't my model save using mongoose and mongodb?

I have a simple Post model and a route to create posts at.我有一个简单的帖子 model 和创建帖子的路线。 When I create one using postman, it loads for a bit and then I get the error json back.当我使用 postman 创建一个时,它会加载一点,然后我得到错误 json 回来。 A model is never saved. model 永远不会被保存。

here is the model:这是 model:

const PostSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    data: {
        type: Date,
        default: Date.now
    }

});

here is the route:这是路线:

router.post('/', (req, res) => {

    console.log(req.body.title);
    console.log(req.body.body);

    const post = new Post({
        title: req.body.title,
        body: req.body.body
    });

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

Everything needed is imported.所需的一切都是进口的。 Please help!请帮忙!

Try using a try{}catch{} like this let me know if there is still an error尝试像这样使用 try{}catch{} 让我知道是否仍有错误

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

    post.save();
    res.status(200).send(`Post created!`);
  } catch (err) {
    res.status(400).send({ message: err });
  }
});

Also check your model is being exported还要检查您的 model 正在导出

const PostSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    data: {
        type: Date,
        default: Date.now
    }

});

module.exports = mongoose.model("Post", PostSchema);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM