猫鼬findByIdAndUpdate

时间:2019-08-15 02:06:12

标签: node.js

我试图使用猫鼬来编辑和更新表单。该代码对我来说似乎很好,但是它不起作用。我已经尝试了很多方法,但是更新的版本仍然相同,我使用放置路由发送表单,当我将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

2 个答案:

答案 0 :(得分:0)

应该指定mongoose返回更新的文档-默认情况下,它返回原始文档(这也是mongodb的行为)。我认为,如果代码更改为此:

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

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

答案 1 :(得分:0)

正如@Denny在回答中所提到的,猫鼬在通过{new : true }选项之前不会在回调中返回更新的文档。 有关详细信息和可用选项,请检查findByIdAndUpdate Docs