Node.js mongoose Model.save()在NodeJS中返回空数据
我试图在NodeJS中使用mongoose v5.6.3将产品文档添加到MongoDB中,但在回调函数中,它无法将结果分配给返回值 以下是我的功能:Node.js mongoose Model.save()在NodeJS中返回空数据,node.js,asynchronous,mongoose,Node.js,Asynchronous,Mongoose,我试图在NodeJS中使用mongoose v5.6.3将产品文档添加到MongoDB中,但在回调函数中,它无法将结果分配给返回值 以下是我的功能: public async addProduct(productInfo: Product) { let result = null; let newProduct = new ProductModel(productInfo); newProduct.uuid = id(); aw
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不同,但参数相同。产品是一个界面,产品模型是一个猫鼬模型
调用此函数时,它返回“result”的初始值
由于异步/等待,可能会出现问题,但我不确定。如何解决此问题?由于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();
}
}
请尝试此代码并让我知道。老兄,很抱歉回答得太晚,这样做很好!多谢各位