首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mongoose findByIdAndUpdate

Mongoose findByIdAndUpdate
EN

Stack Overflow用户
提问于 2019-08-15 10:06:13
回答 2查看 2.7K关注 0票数 0

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

这是我的方案

代码语言:javascript
复制
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

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2019-08-15 16:53:34

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

代码语言:javascript
复制
StudentInfo.findByIdAndUpdate(req.params.id, {$set: req.body.studentInfo}, { new: true }, function(err, updated){
        ...
    });

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

票数 0
EN

Stack Overflow用户

发布于 2019-08-20 16:51:35

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57504070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档