如何在 Mongoose 中推送数组

How to Push an Array in Mongoose

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

    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});
            });
        });
    });
});

这里是return res.send(err)之后的错误详情; :

{
    "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'
    }
});

感谢您的所有回复。

您的代码无法正常工作的原因有多种。

  1. 首先展示架构设计。可能有瑕疵。
  2. 您通过 company.students.push(req.params.id).
  3. 实现
  4. 如果你想推送整个数组,请尝试使用 company.students.push(students).
  5. 记录错误对象。

您正在尝试将字符串转换为 objectId。要保存该值,请使用 mongoose.Types.ObjectId。那会解决你的问题。让我知道是否有帮助。谢谢

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)

Model.findById() 期望参数是有效的 objectID,具有以下描述

  • 一个 4 字节的值,表示自 Unix 纪元以来的秒数,
  • 一个 3 字节的机器标识符
  • 一个 2 字节的进程 ID,并且
  • 一个 3 字节的计数器,以随机值开头。

并且您的错误表明您正试图通过它 "2",这不符合 objectId 标准。您应该将正确的 ID 传递给 findById

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

你可以通过 npm install validator

安装它

并通过

验证 ID

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

ps。 validator 为您提供了验证不同事物的绝妙方法