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);
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.
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.
The insertMany() function is used to insert multiple documents into a collection. It accepts an array of documents to insert into the collection.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With