架构选项_id:false和文档在保存错误发生之前必须具有_id

发布于 2025-02-10 16:54:27 字数 990 浏览 2 评论 0原文

我正在尝试通过这种方式创建一个用户文档:

// create the document ---------------
const id = mongoose.Types.ObjectId()
let userDoc = await Admin.create({ ...req.body, _id: id, by: id })

架构:

adminSchema = new mongoose.Schema({
   // some other fields, firstName, lastName ... etc
   by: {
     type: mongoose.Schema.ObjectId,
     ref: 'Admin',
     required: [true, "the 'by' field is required"],
     immutable: true,
   }
}, { _id: false })

模型:

const Admin = mongoose.model('Admin', adminSchema, 'users')
  • 我的架构没有_id属性。

现在,我想拥有_id字段,并且字段具有相同的值,该值是服务器端生成的ID。

Mongoose正在抛出此错误:

错误:MongooseError:文档在保存之前必须具有_id .../node_modules/mongoose/lib/model.js:291:18

更新:

我更新了我的问题,我添加了架构选项,现在我知道发生了此错误的原因。这是因为我设置的_id:false架构选项。但是我需要此选项,因为我不想在发送给客户的响应中看到_id s。有解决方法吗?因为此选项看起来像是在做两个无关的事情

I am trying to create a user document through this way:

// create the document ---------------
const id = mongoose.Types.ObjectId()
let userDoc = await Admin.create({ ...req.body, _id: id, by: id })

Schema:

adminSchema = new mongoose.Schema({
   // some other fields, firstName, lastName ... etc
   by: {
     type: mongoose.Schema.ObjectId,
     ref: 'Admin',
     required: [true, "the 'by' field is required"],
     immutable: true,
   }
}, { _id: false })

Model:

const Admin = mongoose.model('Admin', adminSchema, 'users')
  • My schema doesn't have an _id property.

Now I want to have the _id field and the by field has the same value, which is a server-side generated id.

Mongoose is throwing this error:

Error: MongooseError: document must have an _id before saving at
.../node_modules/mongoose/lib/model.js:291:18

update:

I updated my question, I added the schema options, and now I know the reason why this error is happening. it's because of the _id: false schema option that I have set. But I need this option because I don't want to see _ids in the responses that I send to the clients. is there a workaround? because this option looks like its doing two unrelated things

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

扛刀软妹 2025-02-17 16:54:27

使用Mongoose 6.4

我通过删除_id:false架构类型选项来解决此问题。

并从响应中删除_id,而不必用_。motit() s或 delete> delete 到处我在模式中添加了以下模式类型选项:

toObject: {
    virtuals: true,
    transform(doc, ret) { 
        delete ret._id
    },
},

现在真正的问题是,为什么在服务器端生成ID时,简单地添加选项_id:false会导致猫鼬错误没有猫鼬的帮助?

错误:MongooseError:文档在保存之前必须具有_id
.../node_modules/mongoose/lib/model.js:291:18

我部分回答了我自己的问题,但是为此,我真的不知道。

Using Mongoose 6.4

I solved this by removing the _id: false schema type option.

and to remove the _id from the responses without having to pollute the routes with _.omit()s or deletes everywhere, I added the following schema type options to the schema:

toObject: {
    virtuals: true,
    transform(doc, ret) { 
        delete ret._id
    },
},

Now the real question is, why does simply adding the option _id: false results in the Mongoose error when you're generating the id on the server-side without the help of Mongoose?

Error: MongooseError: document must have an _id before saving at
.../node_modules/mongoose/lib/model.js:291:18

I partially answered my own question, but for this one... I really don't know.

八巷 2025-02-17 16:54:27

根据您的评论,如果您希望用户收到的响应不包含_id您可以:

  • 获取文档
  • 删除_id属性,并在没有_id (或创建一个新对象以避免问题)。

一个简短的例子可能是:

let responseDoc = await Admin.findOne({ _id: id });
delete responseDoc["_id"]
// responseDoc is now ready for use. Note that if I am not mistaken it is still a document.

Based on your comment, if you want the response the user receives to not contain the _id you can:

  • Get the document
  • Remove the _id property and return this object without the _id (Or create a new object to avoid problems).

A brief example could be:

let responseDoc = await Admin.findOne({ _id: id });
delete responseDoc["_id"]
// responseDoc is now ready for use. Note that if I am not mistaken it is still a document.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文