我尝试使用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发布于 2019-08-15 16:53:34
应该指定mongoose应该返回更新后的文档-默认情况下它返回原始文档(这也是mongodb的行为)。我认为如果代码改成这样:
StudentInfo.findByIdAndUpdate(req.params.id, {$set: req.body.studentInfo}, { new: true }, function(err, updated){
...
});您将在回调中收到更新后的文档。
发布于 2019-08-20 16:51:35
正如@Denny在他的回答中提到的,mongoose不会在回调中返回更新后的文档,直到您传递{new : true }选项。有关详细信息和可用选项,请查看findByIdAndUpdate Docs
https://stackoverflow.com/questions/57504070
复制相似问题