猫鼬模式验证因findOneAndReplace而失败

时间:2020-06-15 08:31:22

标签: node.js mongoose mongoose-schema

使用猫鼬“ findOneAndReplace”更新数据时出现问题, 我收到验证模式错误, 特别是这些字段似乎是空的。

使用相同的数据,我对“创建”和“删除”之类的其他操作没有问题, 因此绝对与架构或数据无关

反正我的代码在这里:

Angular服务

    updateCustomer(customer){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.put(this.UpdateCustomer+'/'+customer._id, JSON.stringify(customer), {headers: headers})
    .map((response: Response) => response.json())
}

猫鼬放下

app.put('/api/aggiorna_cliente/:id', function(req, res, next) {
console.log(JSON.stringify(req.body)) --> IS POPULATED
Clienti.findOneAndReplace(
    {_id:req.params.id},
    {$set:{
        address:req.body.address,
        brand:req.body.brand,
        cap:req.body.cap,
        city:req.body.city,
        civico:req.body.civico,
        email:req.body.email,
        fiscalcode:req.body.fiscalcode,
        provincia:req.body.provincia,
        utente:req.body.utente
        }
    }, 
    function (err, post) {
        if (err) return next(err);
        res.json(post);
    });
});

CLIENTI SCHEMA

            const mongoose = require('mongoose');

        const clientiSchema = mongoose.Schema({
            utente:{
                type: String,
                required:true
            },
            cap:{
                type: Number,
                required:true
            },
            civico:{
                type: String,
                required:true
            },
            city:{
                type: String,
                required:true
            },  
            address:{
                type: String,
                required:true
            },
            fiscalcode:{
                type:String,
                required:true
            },
            email:{
                type:String,
                required:true
            },      
            brand:{
                type:String,
                required:true
            },      
            provincia:{
                province: String,
                sigle: String
            }
        });

        const Clienti = mongoose.model('Clienti',clientiSchema);
        module.exports = Clienti;

那会是什么?

1 个答案:

答案 0 :(得分:0)

不要将$set与Mongoose一起使用(这是Mongo的本机运算符)。第二个参数必须是包含要更新的字段(doc)的对象。不要添加$set。猫鼬认为$set是更新的关键,因此它无法通过验证。

Clienti.findOneAndReplace(
    {_id:req.params.id},
    {
        address:req.body.address,
        brand:req.body.brand,
        cap:req.body.cap,
        city:req.body.city,
        civico:req.body.civico,
        email:req.body.email,
        fiscalcode:req.body.fiscalcode,
        provincia:req.body.provincia,
        utente:req.body.utente
    },