本文介绍了Mongoose保存请求体的所有参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设置一个API,我在我的应用程序的客户端进行一些数据验证,而我这样做,我正在构建我的数据以匹配我的mongoose模式。

I'm setting up a little API, I do some data validation on the client side of my application and whilst I do that I'm structuring my data to match my mongoose schema.

我试图这样做...

router.route('/car')
.post(function(req, res) {
    var car = new Car();

    car = req.body; // line under scrutiny

    car.save(function(err) {
        if(err) {
            console.log(err);
            res.status(400);
            res.send(err);
        }
        else {
            res.status(200);
            res.json({
                message: req.body.name + ' successfully registered!'
            });
        }
    });
});

但当然,这正在删除 car 由mongoose提供,所以保存方法等不再起作用。

but of course, this is currently removing all the model parameters of car provided by mongoose, so the save method e.t.c are no longer functional.

我尝试了 car.data = req。身体,但这需要我的所有的黑猫模式都被包装成一个不太优雅的数据对象。

I have attempted car.data = req.body but this requires all of my mongoose schemas to be wrapped into a data object which isn't so elegant.

我想知道是否有任何方法避免准备 car 对象保存而不用长时间;

I was wondering if there was any way to avoid preparing the car object to be saved without the long-hand of;

car.name = req.body.name;
car.seats = req.body.seats;
car.engine_size = req.body.engine_size; 

我本来是想做相当于 car.push(req.body); ,但再次, .push()方法是

I'm essentially wanting to do the equivalent of car.push(req.body); but again, the .push() method is not available to mongoose models.

推荐答案

您可以通过 req.body 你的 Car 像这样

var car = new Car(req.body);

这里也是一个参考:

这篇关于Mongoose保存请求体的所有参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 06:00