Mongoose insertMany()。exec()返回一个TypeError

时间:2022-12-31 15:47:49

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.

以下函数由async / await函数调用,因此我需要从Mongoose返回一个真正的Promise,因此根据文档和此SO线程使用“.exec()”。

// 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

TypeError:Model.insertMany(...)。exec不是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.

如果我删除exec(),我可以插入很多没有任何问题。我使用exec()的其他查询似乎没有抛出任何错误,这使得它更加令人困惑。

Can someone explain why this is happening?

有人可以解释为什么会这样吗?

Edit 1: Below is my Schema code

编辑1:下面是我的架构代码

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

1 个解决方案

#1


2  

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:

正如在引用中所解释的那样,返回查询的方法可能需要exec(),因为查询不是promise。该引用还列出了返回查询的方法:

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.

insertMany不是其中之一,它立即返回一个承诺。

It should be:

它应该是:

function insertNewResults(data) {
    return Model.insertMany(data);
}

#1


2  

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:

正如在引用中所解释的那样,返回查询的方法可能需要exec(),因为查询不是promise。该引用还列出了返回查询的方法:

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.

insertMany不是其中之一,它立即返回一个承诺。

It should be:

它应该是:

function insertNewResults(data) {
    return Model.insertMany(data);
}