Pregunta

I am beginner in Express. I have the following code in my router/controller for update a model. In one hand I don't want to modify the date of "create_date" parameter, and on the second hand this code returns me a error.

updateFood = function(req, res){
    Food.findById(req.params.id, function(err, food){
        food.food_name = req.body.food_name;
        food.description = req.body.description;
        food.image = req.body.image;
        food.create_date = Date.now();
        food.category = req.body.category;

        Food.save(function(err){
            if (!err){
                console.log("updated!");
            } else {
                console.log(err);
            }
        });

        res.send(food);
    });
};

Here is my schema:

var food = new Schema({
    food_name: {type: String, unique: true},
    description: String,
    image: String,
    create_date: {type: Date, default: Date.now()},
    category: {
        type: String,
        cats: ['Meat', 'Fish', 'Vegetables']
    }
});

module.exports = mongoose.model('Food', food);

When I try to update a food with Postman with PUT. The console returns me the following response:

            Food.save(function(err){
                 ^
TypeError: Object function model(doc, fields, skipId) {
    if (!(this instanceof model))
      return new model(doc, fields, skipId);
    Model.call(this, doc, fields, skipId);
  } has no method 'save'

What can I do? Anyone knows where is my mistake? Thanks.

¿Fue útil?

Solución

I believe you meant food.save(..); instead of Food.save(..);, but if all you're doing is updating the model, you could use findByIdAndUpdate() instead.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top