【问题标题】:How to prevent duplicate documents mongodb with mongoose如何使用猫鼬防止重复文件mongodb
【发布时间】:2019-03-29 11:36:34
【问题描述】:

我在 mongodb 上有一个用户集合和一个投资组合集合。投资组合模型引用用户集合的 objectid。我正在尝试这样做,因此当用户登录并尝试添加他们已有的文档时,路由器会阻止它。现在所有这一切都是查看投资组合集合中的所有文档,但我试图先按用户过滤它,然后搜索名称以查看它是否存在。

  portfolio.find({name: req.body.name})
  .count()
  .then(count => {
    if (count > 0) {
      // There is an existing user with the same username
      res.status(400).json({message: 'Stock already saved!'});
    }else{
     portfolio
     .create({
       user: req.body.user,
       name: req.body.name,
       description: req.body.description,
       symbol: req.body.symbol,
       image: req.body.image,
     })
     .then(portfolioPost => res.status(201).json(portfolioPost.serialize()))
     .catch(err => {
       // console.error(err);
       res.status(500).json({ error: 'Something went wrong' });
     });
    }
  })

这是模型

const listSchema = mongoose.Schema({
  user: { type: mongoose.Schema.Types.ObjectId, ref: "Users" },
  name: { type: String, required: true },
  description: {type:String, required: true},
  image: {type:String},
  symbol: {type: String, required: true}
});

【问题讨论】:

  • 从您的问题中不清楚您想问什么 - 查看代码或解决您遇到的错误或上述代码不起作用的原因?

标签: node.js mongodb express mongoose mongoose-schema


【解决方案1】:

使用 { unique: true } 因此,每当有人尝试对多个投资组合使用相同的用户 ID 时,猫鼬都会抛出错误。

你的模型将是,

const listSchema = mongoose.Schema({
  user: { type: mongoose.Schema.Types.ObjectId, ref: "Users", unique: true },
  name: { type: String, required: true },
  description: {type:String, required: true},
  image: {type:String},
  symbol: {type: String, required: true}
});

我使用了 user 属性 unique。因此,没有两个列表架构可以具有相同的 userId。

最后,您可以跳过查找以前的用户组合。你的代码可以是

portfolio
     .create({
       user: req.body.user,
       name: req.body.name,
       description: req.body.description,
       symbol: req.body.symbol,
       image: req.body.image,
     })
     .then(portfolioPost => res.status(201).json(portfolioPost.serialize()))
     .catch(err => {
       // console.error(err);
       res.status(500).json({ error: 'Something went wrong' });
     });

这种情况下,如果已经有当前userId的投资组合,MongoDB会报错。

更多详情,请查看Additional Options部分。

【讨论】:

  • 这无济于事,因为唯一键是在 mongodb 中创建唯一索引,而不是在保存之前检查数据的重复作为验证部分。
猜你喜欢
  • 2020-03-23
  • 1970-01-01
  • 2017-10-08
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2018-10-30
相关资源
最近更新 更多