This question already has an answer here:
why mongoose queries dos not work when put inside promise function
                                
                                    (1个答案)
                                
                        
                                2年前关闭。
            
                    
我一直在尝试从TransactionType架构获取ID并将其用作新类别中的引用,但它总是在完成对新TransactionType的查询之前调用创建新类别。

const Category = require("../models/categories.model");
const TransactionType = require("../models/transactiontype.model");
async function saveNewCategory(req, res, next) {
    let transactionID;
    const transID = await TransactionType.findOne({ name: req.body.transactionType })
        .populate("transactionType")
        .exec((error, res) => {
            console.log(res.id);
            transactionID = res.id;
            console.log(transactionID);
            return transactionID;
        });

    const newCategory = await new Category({
        name: req.body.name,
        transactionType: transactionID || transID ,
        image: req.body.image,
        description: req.body.description
    });
    try {
        await newCategory.save();
        await res
            .status(200)
            .send({ response: "Response " + JSON.stringify(req.body, undefined, 2) });
    } catch (error) {
        console.log(error);
    }
};
module.exports = {
    saveNewCategory
};


在完成transID之前,它将创建带有transactionType未定义的newCategory。
请在以下类别模式下找到。

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const category = new Schema({
    name: String,
    transactionType : {
        type: Schema.Types.ObjectId,
        ref: "TransactionType"
    },
    image: String,
    description: String
});

const Category = mongoose.model('Category', category);
module.exports = Category;


在TransactionType模型下面找到

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const transactionType = new Schema({
    transaction: String
});
const TransactionType = mongoose.model('TransactionType', transactionType);
module.exports = TransactionType;


如果有人可以帮助我理解这一点,我将不胜感激。我浏览了许多书籍和博客,以了解异步等待,但仍然没有答案。

最佳答案

我认为您可以将所有异步内容放入立即异步功能中。这样,saveNewCategory就不会在您的异步操作完成之前结束。

async function saveNewCategory(req, res, next) {
    (async () => {
      await asyncStuff()
    })()
}


编辑:为了更好地了解异步等待和承诺,请查看本文:
https://pouchdb.com/2015/03/05/taming-the-async-beast-with-es7.html

07-28 10:48