【问题标题】:How to inset multiple documents in mongoose with mongoose required validation?如何使用猫鼬需要验证在猫鼬中插入多个文档?
【发布时间】:2020-02-16 01:58:43
【问题描述】:

我想在我的 MongoDB 集合中插入多个文档。我可以通过使用 Model.collection.insert 函数来做到这一点,但是当我插入这些数据时,它会跳过/绕过所需的验证。

我已经尝试过Model.collection.insert([{data: '1'}, {data: '2'}, {type: '3'}]),但这样会跳过或绕过验证。我希望需要数据字段,并根据需要在我的架构中使用。但这不起作用。

我的架构需要一个字段。

export const SubjectSchema = new mongoose.Schema({
    title: { type: String, required: [true, "title field required"] },
    groups_id: { type: String },
    class_id: { type: String },
    meta: { type: Object }
},
    { timestamps: true })

这是我的功能

    async createSubject(body) {
        let result = SubjectSchema.collection.insert(body)
        return result
    }

我想要存储多个数据,并且在每条记录中,title 字段应该是必需的

【问题讨论】:

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


    【解决方案1】:
    Model.insertMany([{data: '1'}, {data: '2'}, {type: '3'}])
    

    你可以找到insertMany ref here

    不过,你也可以db.collection.validate()

    【讨论】:

    • 兄弟,我想要那些单个对象作为验证。请参阅上面我尝试过的内容。我要验证。我知道如何插入许多文档,但我担心这种方式会跳过验证。和存储没有title
    • 试试猫鼬中间件SubjectSchema.pre('save', validationFunction);
    • 看起来这个答案会起作用,因为在猫鼬文档中,它说:猫鼬总是在将 insertMany 发送到 MongoDB 之前验证每个文档。
    • 乐于助兄^_^
    猜你喜欢
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2016-09-23
    相关资源
    最近更新 更多