【问题标题】:Mongoose findByIdAndUpdate猫鼬 findByIdAndUpdate
【发布时间】:2019-08-20 16:51:34
【问题描述】:

我尝试使用 mongoose 编辑和更新表单。代码对我来说似乎很好,但它不起作用。尝试了很多方法,但更新后的版本还是一样,我使用put路由发送表单,当我将req.body.studentInfo输出到控制台时,它是正确的,但更新还是一样的。请帮忙

这是我的架构

var mongoose = require("mongoose");
var uniqueValidator = require('mongoose-unique-validator');
var passportLocalMongoose = require("passport-local-mongoose");
var mongoose = require("mongoose");

var UserSchema = new mongoose.Schema({
   studentInfo: {
   first_name: String,
   middle_name: String,
   last_name: String,
   street: String,
   town: String,
   city: String,
   region: String,
   country: String,
   studentId: String,
   day: Number,
   month: String,
   year: Number,
   },                   
   username: {type: String, required:true, unique:true},
   passport: String

});
UserSchema.plugin(uniqueValidator);
UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("StudentInfo", UserSchema);

这是我的 App.js

app.put('/:id', function(req,res){
    StudentInfo.findByIdAndUpdate(req.params.id, {$set: req.body.studentInfo}, function(err, updated){
        console.log(req.params.id);
        console.log(req.body.studentInfo);
        if(err) {
            console.log(err);
        }
        else {
            res.redirect('/' + req.params.id);
        }
    });

});

The studentInfo is an object that contains the names of each variables in my form which I name was studentInfo[name of variable]. Please help

【问题讨论】:

  • 你能控制台输出吗?
  • 你试过findOneAndUpdate()吗?
  • 是否必须使用id作为参数和少数.body
  • 还是不行
  • @user8628552,希望对您有所帮助! stackoverflow.com/questions/53554434/…

标签: node.js


【解决方案1】:

应该指定mongoose应该返回更新后的文档——默认返回原始文档(这也是mongodb的行为)。我认为如果代码更改为:

StudentInfo.findByIdAndUpdate(req.params.id, {$set: req.body.studentInfo}, { new: true }, function(err, updated){
        ...
    });

您将在回调中收到更新的文档。

【讨论】:

    【解决方案2】:

    正如@Denny 在他的回答中提到的,mongoose 不会在回调中返回更新的文档,直到您通过 {new : true } 选项。 有关详细信息和可用选项,请查看findByIdAndUpdate Docs

    【讨论】:

      猜你喜欢
      • 2017-01-16
      • 2023-03-03
      • 1970-01-01
      • 2019-09-10
      • 2020-09-06
      • 2020-09-05
      • 2022-07-21
      • 2018-04-25
      • 2015-08-05
      相关资源
      最近更新 更多