mongoose model.remove给出modelname.remove(...).exec不是函数

uelo1irk  于 2023-08-06  发布在  Go
关注(0)|答案(2)|浏览(136)

我不断收到此错误:

Mongoose: invoice.remove({ _id: 3 }, {})
TypeError: invoiceRecord.remove(...).exec is not a function

字符串
我试图删除.exec,但它将无法识别我的函数(错误,数据)
这是我的函数

var deleteInvoice = () => {
    return new Promise((resolve, reject) => {
    invoiceRecord.remove(
    ).exec(function (err, data) {  
        if (err) {
            reject(new Error('deleteInvoice ERROR : ' + err));
            return;
        }
        if (data.result.n == 0) {
            reject({code:"INVOICE_NOTFOUND", err:"This invoice could not be found: " + invoiceRecord._id});
            return;
        }
        resolve(data);
    })
})};


当我的invoiceRecord已经有需要删除的数据时,我该如何执行此操作?
这个方法的作用是:

invoiceTable.remove (
    { _id: invoiceRecord._id }
,function(err, data) {


这不会:

invoiceRecord.remove (
        { _id: invoiceRecord._id }
    ,function(err, data) {


我真的不明白为什么

f4t66c6m

f4t66c6m1#

此处记录了正确的语法。
由于所有的异步Mongoose方法都已经返回promise,你的代码可以重写为:

var deleteInvoice = () => {
  return invoiceRecord.remove().then(data => {
    if (data.result.n === 0) {
      // ATTN: it's better to throw Error instances
      throw { code:"INVOICE_NOTFOUND", err:"This invoice could not be found: " + invoiceRecord._id };
    }
  }, err => {
    err.message = 'deleteInvoice ERROR : ' + err.message;
    // Re-throw error
    throw err;
  })
})};

字符串

wfauudbj

wfauudbj2#

Mongoose中的remove()方法已被弃用,取而代之的是deleteOne()deleteMany()。因此,建议使用deleteOne()删除单个文档。

相关问题