如何在我的 Express Server 中修复此更新方法以说明 Mongoose Schema 中的数组

How to fix this update method in my Express Server to account for an array in a Mongoose Schema

我正在使用 express、mongodb 和猫鼬构建 REST Api。作为我的模式的一部分,我已经声明我想要一个数组来保存值列表。我无法使用邮递员添加或更新数组中的值。我基本上想知道为什么这不起作用以及这种情况的最佳做法是什么。

这是我的猫鼬模式

const Schema = mongoose.Schema;

let Quote = new Schema({
    name: {
        type: String,
    },
    quote: [String],
    date_submitted: {
        type: Date,
        default: Date.now,
    },
});

module.exports = mongoose.model('Quote', Quote);

如前所述,我有一个数组设置来保存多个引号。

这里是给mongoDB添加引号的方法:

    let quote = new Quotes({
        name: req.body.name,
        quote: req.body,
    });
    quote
        .save()
        .then(quote => {
            res.status(200).send('adding new quote successful');
        })
        .catch(err => {
            res.status(400).send('adding new quote failed' + err);
        });
}); 

这确实会向数据库添加一条记录,但我不确定这种方法是否是最佳做法。

这是根本不起作用的更新方法

router.post('/update/:id', (req, res) => {
    // Quotes.findOneAndUpdate({ name: req.body.name }, { $push: { quote: req.body.quote } });
    Quotes.findById(req.params.id, function(err, quote) {
        if (!quote) {
            res.status(404).send('Data is not found');
        } else {
            quote.author = req.body.name;
            quote.quotes = { $push: { quote: req.body.quote } };
            quote.date_submitted = req.body.date_submitted;

            quote
                .save()
                .then(quote => {
                    res.json('quote updated');
                })
                .catch(err => {
                    res.status(400).send('Update not possible' + ' ' + err);
                });
        }
    });
});

您可以看到我尝试执行 findOneAndUpdate 方法,但它没有像它应该的那样将值推送到数组中。当我从 Postman 提交我的 POST 请求时,我没有收到错误,但是当我检查数据库时,数组值保持不变。在这方面的任何帮助都会很棒!

您可以尝试使用简单的 array#push 将报价推送到 quote.quote,然后保存文档。 quote.quote.push(req.body.quote)