繁体   English   中英

在猫鼬模式子文档中使用async / await [重复]

[英]using async/await in mongoose schema subdocument [duplicate]

这个问题已经在这里有了答案:

我一直在尝试从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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM