MongoError:对路径“ _id”执行更新会修改不可变字段“ _id”

时间:2018-08-14 09:06:32

标签: node.js mongodb mongoose

每当我尝试更新value的计数时,都会显示错误:

MongoError: Performing an update on the path '_id' would modify the immutable field '_id'

没有更新功能,代码可以正常工作,但是在放置路径中使用更新查找会出现错误。

如果它的键值等于通过编辑路径获得的值,我想将polls对象中选项的值增加1。

var express      =require("express");
var app          =express();
var bodyParser   =require("body-parser");
var mongoose     =require("mongoose");
var methodOverride=require("method-override");
app.use(bodyParser.urlencoded({extended:true}));
app.set("view engine","ejs");
app.use(methodOverride("_method"));
mongoose.connect("mongodb://localhost/vtapp");
var pollSchema=new mongoose.Schema({
    name:String,
    options:[{key:String,value:Number}]
});
var Poll=mongoose.model("Poll",pollSchema);

app.get("/",function(req,res){
    Poll.find({},function(err,allpolls){
        if(err){
            console.log(err);
        }
        else
        {
            res.render("landing",{polls:allpolls}); 
        }
    });
});
app.post("/",function(req,res){
    var name=req.body.name;
    var text=req.body.options;
    var arrops=text.split("\n");
    var newpoll={name:name,options:[]};
    arrops.forEach(function(opt){
        newpoll.options.push({key:opt,value:0});
    });
    Poll.create(newpoll,function(err,newp){
        if(err){
            console.log(err);
        }
        else
        {
            res.redirect("/");
        }
    });
});
app.get("/new",function(req,res){
    res.render("new");
});
app.get("/pollshow/:id/edit",function(req,res){
    Poll.findById(req.params.id,function(err,foundpoll){
        if(err){
            console.log(err);
        }
        else
        {
            res.render("show",{poll:foundpoll});
        }
    });
});
app.put("/pollshow/:id",function(req,res){
    Poll.findById(req.params.id,function(err,found){
        if(err){
            console.log(err);
        }
        else
        {
            found.options.forEach(function(option){
                if(option.key==req.body.choice){
                    found.update(option,{$inc:{value:1}},function(err){
                        if(err) {console.log(err);}
                    });
                }
            });
            res.redirect("/pollshow/"+req.params.id+'/edit');
        }
    });
});
app.listen(process.env.PORT,process.env.IP,function(){
    console.log("Application is running");
});

如果我不修改id,错误怎么来?

0 个答案:

没有答案