2
votes

I'd like to update data with push an array into the document, but I got an error in res.send(err), here is my code :

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

Here is the error details after 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"
}

Update, this is My Schema, I'd like to add id user from UserSchema to students in 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'
    }
});

Thank you for all of your responses.

4
Your code is returning that error "Cannot Update Company, please try again". Instead of doing that, why don't you also include information from the object "err", instead of discarding it. It will give you more of a clue about what's happening.goamn
I would suggest that you print the company object and also print the err object. This will give you more idea about what is going wrong. Maybe the data is not coming exactly like your model needs it.Ishan Koul
In your schema students should be declared as an array like students: [{ type : mongoose.Schema.Types.ObjectId,ref : 'users' }]chridam

4 Answers

1
votes

You are trying to convert a string into objectId. For saving that value, use mongoose.Types.ObjectId. That will solve your problem. Let me know if it helps. Thanks

0
votes

Well there are multiple reasons that why your code is not working.

  1. Firstly show the schema design. May be there is a flaw.
  2. You achieve this by company.students.push(req.params.id).
  3. If you want to push the whole array try using, company.students.push(students).
  4. Log the error object.
0
votes
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
votes

Model.findById() expects the parameter to be a valid objectID with the following descriptions

  • a 4-byte value representing the seconds since the Unix epoch,
  • a 3-byte machine identifier
  • a 2-byte process id, and
  • a 3-byte counter, starting with a random value.

And your error states that you are trying to pass it "2" which doesn't follow the objectId standards. You should pass the correct id to findById.

You can use validator to make sure whether your passed id parameter is correct or not. Something like

well you can install it by npm install validator

And validate the id by

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

ps. validator gives you really handsome ways to validate different things