0

I wanted to insert multiple documents in my MongoDB collection. I was able to do that by using Model.collection.insert function but when I insert those data it skip/bypass required validation.

I've tried Model.collection.insert([{data: '1'}, {data: '2'}, {type: '3'}]) but this way it's skip or bypass the validation. I want data field required and I used in my Schema that as required. But that's not working.

There is my schema that required a field.

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 })

Here is my function

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

I want multiple data to be stored and in each record, title field should be required

1 Answer 1

1
Model.insertMany([{data: '1'}, {data: '2'}, {type: '3'}])

you can find the insertMany ref here

however, you can also db.collection.validate()

4
  • Brother, I wanted those single objects as validate. See above what I tried yet. I want validation. I know how to insert many documents but my concern is this way it is skipping validation. And storing without title Oct 19, 2019 at 7:48
  • try mongoose middlewares SubjectSchema.pre('save', validationFunction); Oct 19, 2019 at 7:51
  • 1
    Look like this answer will work because in mongoose docs, it says that: Mongoose always validates each document before sending insertMany to MongoDB. Oct 19, 2019 at 7:54
  • 1
    happy to help brother ^_^ Oct 19, 2019 at 8:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.