Mongo递增ID问题

尤拉杰·雅库博夫

我正在尝试在用户中增加 id。我尝试了两种方法,但在这两种方法中,我都遇到错误。

a)
型号

const userSchema = new mongoose.Schema({
  _id: {
    type: Number,
    unique: true
  },  ....

控制器

const user = new User({
    profile: {
      _id: core.getNextSequenceValue('userid'),
      firstname: req.body.firstname,
      lastname: req.body.lastname,
      location: req.body.location,....

我得到的错误

mongoose: Cannot specify a custom index on `_id` for model name "User", MongoDB does not allow overwriting the default `_id` index. See

b)
型号

const userSchema = new mongoose.Schema({
  id: {
    type: Number,
    unique: true
  },  ....

控制器

const user = new User({
id: core.getNextSequenceValue('userid'),
    profile: {
      firstname: req.body.firstname,
      lastname: req.body.lastname,
      location: req.body.location,....

我得到的错误

 Error: Failed to serialize user into session

有什么方法可以在不降级的情况下将 _id 设置为自定义编号(从 1 到 ...)?或者我需要创建新的自定义 id 像idx

吉特

_id 字段在 mongodb 中真的很特别。这是您的主键,没有它您就无法拥有文档。即使您不能为您的集合修改 _id 字段。

但是您可以使用自己的 _id 创建文档。所以如果你愿意,你可以做db.users.insert({"_id":"1","User_Name":"avbd"})

并记住 _id 表示 user_id 并且 _id 应该是唯一的

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章