如何在具有 mongodb 的 nodejs 中将函数写入 return 所有元素而不是仅创建

How in nodejs with mongodb write function to return all elements instead of only just created

我想在 crud 应用程序中编写函数,它在保存元素后 returns 所有元素而不是刚刚创建的。

我写了那个函数:

exports.create = (req, res) => {
    if (req.body.content)
        return res.status(400).send({ message: 'Rule content can not be empty' });
    
    const rule = new Rule({ rulename: req.body.rulename || 'Empty Rule' });
    rule.save()
        .then(() => {
            Rule.find().then(rules => {
                res.send(rules);
            })
        })
        .catch(err => { res.status(500).send({ message: err.message || 'Some error occured while creating the Rule' }) });
}

我工作了,但我该如何改进它?

我建议您使用 async/await 而不是 Promise 链接方法:

exports.create = async (req, res) => {
    if (!req.body.content)
        return res.status(400).send({ message: 'Rule content can not be empty' });

    const rule = new Rule({ rulename: req.body.rulename || 'Empty Rule' });
    try {
        await rule.save();
        const rules = await Rule.find();
        return res.status(200).send(rules);
    } catch (e) {
        res.status(500).send({ message: err.message || 'Some error occured while creating the Rule' });
    }
}

如您所知,它不会改变您的代码性能,但它以线性样式而不是 Promise 链中的嵌套回调函数更具可读性。