在猫鼬模式子文档中使用async / await

时间:2018-11-23 07:40:03

标签: javascript node.js mongoose schema

我一直试图从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;

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

1 个答案:

答案 0 :(得分:0)

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

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

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