【问题标题】:mongoose Model.save() returns null data in NodeJSmongoose Model.save() 在 NodeJS 中返回空数据
【发布时间】:2019-11-30 07:56:18
【问题描述】:

我正在尝试通过在 NodeJS 中使用 mongoose v5.6.3 将产品文档添加到 MongoDB,但在回调函数中,它无法将结果分配给返回值。

这是我的功能:

public async addProduct(productInfo: Product) {
        let result = null;

        let newProduct = new ProductModel(productInfo);
        newProduct.uuid = id();

        await newProduct.save(async (err,product) => {
            if(err){
                throw new ProductCreateError();
            }
            result = product;
        });
        return result;
    }

请注意,Product 和 ProductModel 在参数方面不同但相同。 Product 是一个接口,ProductModel 是一个猫鼬模型。

调用此函数时,返回'result'的初始值

由于 async/await 可能会出现问题,但我不确定。我该如何解决这个问题?

【问题讨论】:

    标签: node.js asynchronous mongoose


    【解决方案1】:

    由于 save() 是一个异步任务,它总是返回 null。该函数将在返回产品之前返回 null。

    修改代码为

    public async addProduct(productInfo: Product) {
    let result = null;
      try {
        let newProduct = new ProductModel(productInfo);
        newProduct.uuid = id();
        result = await newProduct.save();
      } catch (e) {
        throw new ProductCreateError();
      }
    }
    

    试试这个代码,让我知道。

    【讨论】:

    • 老兄很抱歉回答迟了,这很好用!非常感谢
    猜你喜欢
    • 2020-09-16
    • 2021-12-27
    • 2012-12-20
    • 1970-01-01
    • 2013-08-19
    相关资源
    最近更新 更多