代码之家  ›  专栏  ›  技术社区  ›  Normal

schema选项_id:false,文档在保存错误之前必须有一个_id

  •  0
  • Normal  · 技术社区  · 2 年前

    我正试图通过以下方式创建用户文档:

    // 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 字段和 by 字段具有相同的值,即服务器端生成的id。

    Mongoose正在抛出此错误:

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

    更新:

    我更新了我的问题,添加了模式选项,现在我知道了发生这个错误的原因。这是因为 _id: false 我设置的schema选项。但我需要这个选择,因为我不想看到 _id s在我发送给客户的回复中。有变通办法吗?因为这个选项看起来像是在做两件不相关的事情

    0 回复  |  直到 2 年前
        1
  •  1
  •   Normal    2 年前

    使用Mongoose 6.4

    我通过删除 _id: false 架构类型选项。

    并且从响应中移除_id而不必用 _.omit() s或 delete 到处都是,我在架构中添加了以下架构类型选项:

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

    现在真正的问题是,为什么简单地添加选项 _id:false 当你在没有Mongoose帮助的情况下在服务器端生成id时,会导致Mongoose错误吗?

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

    我部分回答了我自己的问题,但对于这个问题。。。我真的不知道。

        2
  •  0
  •   Teyrox    2 年前

    根据您的评论,如果您希望用户收到的响应不包含 _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.