是否有任何解决方案可以消除 MongoDB 中的重复键错误

问题描述 投票:0回答:1

我正在创建 pinterest 克隆,但在上传帖子时遇到一些问题。问题在于尝试保存第二篇文章时出现重复键错误等等。

这是我的用户架构:

const mongoose = require('mongoose');
const plm = require('passport-local-mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/DataVault');


const userSchema = new mongoose.Schema({
  username: {
    type: String,
    unique: true
  },
  email: {
    type: String,
  },
  password: String,

  post: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Post",
    }
  ],
  ProfileImage: String,
});

userSchema.plugin(plm);

module.exports = mongoose.model('User', userSchema);

这是我的帖子架构:

const mongoose = require('mongoose');
const plm = require('passport-local-mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/DataVault');

const postSchema = new mongoose.Schema({
  PostText: {
    type: String,
  },
  image: {
    type: String
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  }
});

postSchema.plugin(plm);

module.exports = mongoose.model('Post', postSchema);

这是我创建帖子并保存的路线

// post creaetion and uploading
router.post("/postUpload", isLoggedIn, uploads.single("postImage"), async function (req, res, next) {
  if (!req.file) {
    return res.status(404).send("Something Went Wrong!!!😡");
  }

  const user = await userModel.findOne({ username: req.session.passport.user });
  const post = await postModel.create({
    PostText: req.body.fileCaption,
    image: req.file.filename,
    user: user._id
  });

  user.post.push(post._id);
  await user.save();

  console.log("Post Successfully Saved ✌");
  res.redirect("/profile");
});

这是我使用同一帐户(用户)上传第二篇文章时遇到的错误:

抛出新的 error_1.MongoServerError(res.writeErrors[0]);
^

MongoServerError:E11000重复键错误集合:DataVault.posts索引:username_1 dup key:{用户名:null}

在 InsertOneOperation.execute (D: ackend\Codes\pinterest ode_modules\mongodb\lib\operations\insert.js:48:19)
在 process.processTicksAndRejections (节点:内部/进程/task_queues:95:5)
在异步executeOperationAsync (D: ackend\Codes\pinterest ode_modules\mongodb\lib\operations xecute_operation.js:106:16) {
索引:0,
代码:11000,
keyPattern: { 用户名: 1 },
keyValue: { 用户名: null },
[符号(错误标签)]:设置(0){}
}

node.js database mongodb post
1个回答
0
投票

错误来自您的

userModel.findOne
,没有返回。所以
user.save()
将创建一个用户名为 null 的新用户。之后,客户端调用 api,但结果
findOne by usename
不再是,这使得服务器创建一个新用户并使用 username = null 进行复制。

要解决此错误,您可以在

userModel.findOne
后检查用户的结果。例如:
if (!user) return res.status(400).send("User not found!");

router.post("/postUpload", isLoggedIn, uploads.single("postImage"), async function (req, res, next) {
  if (!req.file) {
    return res.status(404).send("Something Went Wrong!!!😡");
  }

  const user = await userModel.findOne({ username: req.session.passport.user });
  // Check user exist before create post
  if (!user) return res.status(400).send("User not found!");
  const post = await postModel.create({
    PostText: req.body.fileCaption,
    image: req.file.filename,
    user: user._id
  });

  user.post.push(post._id);
  await user.save();

  console.log("Post Successfully Saved ✌");
  res.redirect("/profile");
});
© www.soinside.com 2019 - 2024. All rights reserved.