【发布时间】:2021-07-10 01:09:56
【问题描述】:
我正在设置一个简单的博客表单,其中包含标题、内容和json base64 图像数据以传递到本地 MongoDB 服务器。这是我的发帖路线:
router.post('/:userName/posts/new', isAuthenticated, async (req, res) => {
let parsedImage = req.body.file != null && req.body.file != '' ? JSON.parse(req.body.file).data : ''
const newPost = new Post({
title: req.body.title,
content: req.body.content,
imageJson: parsedImage
})
try {
await newPost.save()
res.redirect("/account")
} catch (e) {
console.log(e)
res.redirect("/home")
}
})
这是我的模式模型:
const mongoose = require('mongoose');
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
imageJson: {
type: String
}
});
module.exports = mongoose.model('Post', postSchema)
如您所见,没有unique: true。我第一次尝试运行它时,它运行完美,直接重定向到 /account 页面,正如 try catch 块中所预期的那样。但是,在第二次尝试时,使用不同的图像、不同的内容和不同的标题,它抛出了这个错误:
MongoError: E11000 duplicate key error collection: fullstacksus.posts index: userName_1 dup key: { userName: null }
我不知道发生了什么,因为 userName 是在我的用户帐户 route 中使用的数据库名称,但不是在我的帖子制作 route 中使用的数据库名称。为什么又出现了?感谢您的回答。
【问题讨论】:
-
db.posts.getIndexes()显示什么? -
显示:
[ ]
标签: node.js database mongodb mongoose unique