Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose insertMany().exec() returning a TypeError

The following function is called by an async/await function and therefore I need a real Promise to be returned from Mongoose hence the use of ".exec()" per the documentation and this SO thread.

// where data is an array of documents
function insertNewResults(data) {
    return Model.insertMany(data).exec();
}

Doing so gives me the following error:

TypeError: Model.insertMany(...).exec is not a function at insertNewResults

If I remove exec(), I'm able to insertMany without any issues. My other queries using exec() don't seem to be throwing any errors, which makes it all the more perplexing.

Can someone explain why this is happening?

Edit 1: Below is my Schema code

const mongoose = require('mongoose');

const schema = new mongoose.Schema({
    date: { type: Date, required: true },
    price: { type: Number, required: true },
    result: { type: String, required: true }
}, { usePushEach: true });

schema.index(
    { date: -1 }
);
mongoose.model('Model', schema);
like image 222
p4t Avatar asked Jul 21 '18 07:07

p4t


People also ask

What does insertMany return mongoose?

insertMany() method returns a document containing: A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled. An array of _id values for each successfully inserted document.

What is exec is used in mongoose?

In Mongoose queries are composed but not necessarily run immediately. They return a query object that you can add (or chain) other queries to. The queries are all run as a unit when needed so there isn't any storing of unneeded intermediate results. This is what the exec() function does.

How do I save multiple documents in Mongodb?

The insertMany() function is used to insert multiple documents into a collection. It accepts an array of documents to insert into the collection.


1 Answers

As it's explained in the reference, exec() may be needed for methods that return queries because queries are not promises. The reference also lists methods that return queries:

Model.deleteMany()
Model.deleteOne()
Model.find()
Model.findById()
Model.findByIdAndDelete()
Model.findByIdAndRemove()
Model.findByIdAndUpdate()
Model.findOne()
Model.findOneAndDelete()
Model.findOneAndRemove()
Model.findOneAndUpdate()
Model.replaceOne()
Model.updateMany()
Model.updateOne()

insertMany isn't one of them, it returns a promise right away.

It should be:

function insertNewResults(data) {
    return Model.insertMany(data);
}
like image 153
Estus Flask Avatar answered Sep 20 '22 02:09

Estus Flask