Mongoose: what's the differences between Model.create and Collection.insert

前端 未结 3 1487
旧时难觅i
旧时难觅i 2020-12-14 18:20

I want do a batch insert job in MongoDB and I found two ways in mongoose:

One way is use insert:

dataArr = [
   {
       id: \"\",
              


        
相关标签:
3条回答
  • 2020-12-14 18:40

    according to what i've read, Collection.insert is a function of mongoDB driver it's much faster when inserting big amounts of data like millions or such at the cost that it bypasses mongoose validations.

    handle with care

    0 讨论(0)
  • 2020-12-14 18:55

    In Mongoose, there is Model.create and Collection.insert (the latter isn't strictly part of Mongoose, but of the underlying MongoDB driver).

    According to the Mongoose developer, they are basically the same when called with an array of documents, although looking at the code makes me think that there are subtle differences (warning: I haven't looked at the code that well so I might be mistaken about the following):

    • using Model.create will call any validators/hooks declared on your schema;
    • Model.create does a .save for each document in the array, resulting in N database calls (where N is the number of documents in the array); Collection.insert performs one large database call;
    0 讨论(0)
  • 2020-12-14 19:03

    They loosely mean the same thing. You can use either of them.

    0 讨论(0)
提交回复
热议问题