简体   繁体   English

更新/放置错误保存在Express和Mongoose中

[英]Update/Put error save in Express and Mongoose

I am beginner in Express. 我是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. 一方面,我不想修改“ create_date”参数的日期,另一方面,此代码向我返回错误。

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. 当我尝试通过邮递员使用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. 谢谢。

I believe you meant food.save(..); 我相信您的意思是food.save(..); instead of Food.save(..); 而不是Food.save(..); , but if all you're doing is updating the model, you could use findByIdAndUpdate() instead. ,但是如果您要做的只是更新模型,则可以改用findByIdAndUpdate()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM