How to save an array of objects to mongoose DB with only one call?

后端 未结 5 1698
野的像风
野的像风 2020-12-29 07:34

Is there any way to save an array of JSON object to a mongodb with only one call? something like:

schemeObject.save(array_of_json_object, ca         


        
5条回答
  •  离开以前
    2020-12-29 08:01

    Another workaround that I've used. If you are using mongoose with promises, you can do this using Q.

    You can start using Q as the default promise for mongoose using the below code:

    const mongoose = require('mongoose');
    mongoose.Promise = require('q').Promise;
    

    Then you can save an array of documents like below. Let's say we are storing an array of User models, which I've shown in users variable.

    Q
      .all(users.map(curr => curr.save()))
      .then((results) => { //do something })
      .catch((err) => { //handle error })
    

    .save() will return a q promise and using array map function, we'll create a promise array using the user models array.

提交回复
热议问题