首页 文章

如何在Mongoose中推送数组

提问于
浏览
2

我想通过将数组推入文档更新数据,但我在res.send(错误)中出错,这是我的代码:

router.put('/update/:id', passport.authenticate('jwt', {session:false}), (req, res, next)=>{
    User.findById(req.params.id, function(err, user) {
        if(err) {
            console.log(err);
            return res.status(500).send({message: "Error"});
        }
        if(!user) {
            return res.status(404).send({message: "User Not Found"});            
        }
        Company.findById(req.body.company, function(err, company) {
            var students = [req.params.id];
            company.students = students.push(req.params.id);
            // res.send(students);
            company.save(function(err, company){
            if(err){
                return res.send(err);
                // return res.status(500).send({message: "Cannot Update Company, please try again"});
            }
                return res.status(200).send({message: "Update User To Company Success.", company});
            });
        });
    });
});

这是返回res.send(错误)后的错误详细信息; :

{
    "errors": {
        "students": {
            "message": "Cast to ObjectID failed for value \"2\" at path \"students\"",
            "name": "CastError",
            "stringValue": "\"2\"",
            "kind": "ObjectID",
            "value": 2,
            "path": "students",
            "reason": {
                "message": "Cast to ObjectId failed for value \"2\" at path \"students\"",
                "name": "CastError",
                "stringValue": "\"2\"",
                "kind": "ObjectId",
                "value": 2,
                "path": "students"
            }
        }
    },
    "_message": "Company validation failed",
    "message": "Company validation failed: students: Cast to ObjectID failed for value \"2\" at path \"students\"",
    "name": "ValidationError"
}

更新,这是我的架构,我想将UserSchema中的id用户添加到CompanySchema中的学生:

const CompanySchema = mongoose.Schema({
    nama:{
        type    : String,
        require : true
    },
    alamat:{
        type    : String,
        require : true
    },
    email:{
        type    : String,
        require : true
    },
    telepon:{
        type    : String,
        require : true
    },
    website:{
        type    : String,
        require : true
    },
    status:{
        type    : String,
        require : true
    },
    students:{
        type : mongoose.Schema.Types.ObjectId,
        ref  : 'users'
    }
});

const CompanySchema = mongoose.Schema({
    nama:{
        type    : String,
        require : true
    },
    alamat:{
        type    : String,
        require : true
    },
    email:{
        type    : String,
        require : true
    },
    telepon:{
        type    : String,
        require : true
    },
    website:{
        type    : String,
        require : true
    },
    status:{
        type    : String,
        require : true
    },
    students:{
        type : mongoose.Schema.Types.ObjectId,
        ref  : 'users'
    }
});

感谢您的所有回复 .

4 回答

  • 0
    you are making two mistakes here
        1) your schema type is ObjectId but you are pushing string
          cast string to ObjectId : mongoose.Types.ObjectId
        2) storing in students an array,which would become something like this
           => var students=[ObjectId('')]
        3) now again before assinging to company.students you are pushing the 
                same objectId to students variable
        try following lines
    
    // var students = [req.params.id];you don't need this line
            company.students.push(req.params.id)
    
  • 0

    好吧,有多种原因导致您的代码无效 .

    • 首先显示架构设计 . 可能存在缺陷 .

    • 您通过 company.students.push(req.params.id) 实现此目的 .

    • 如果要推送整个阵列,请尝试使用 company.students.push(students) .

    • 记录错误对象 .

  • 0

    您正在尝试将字符串转换为objectId . 要保存该值,请使用mongoose.Types.ObjectId . 这将解决您的问题 . 如果有帮助,请告诉我 . 谢谢

  • 1

    Model.findById() 期望参数有效 objectID ,并带有以下描述

    • 一个4字节的值,表示自Unix纪元以来的秒数,

    • 一个3字节的机器标识符

    • 一个2字节的进程ID,和

    • 一个3字节计数器,以随机值开头 .

    并且您的错误表明您正在尝试传递 "2" ,这不遵循 objectId 标准 . 您应该将正确的ID传递给 findById .

    您可以使用 validator 来确定传递的 id 参数是否正确 . 就像是

    你可以通过 npm install validator 安装它

    并通过验证身份

    if(!validator.isMongoId(req.headers.postid)){ res.send("invalid post id ") }

    PS . validator 为您提供了非常漂亮的方法来验证不同的东西

相关问题