【问题标题】:How to Push an Array in Mongoose如何在 Mongoose 中推送数组
【发布时间】:2018-09-14 19:50:23
【问题描述】:

我想通过将数组推送到文档来更新数据,但我在 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});
            });
        });
    });
});

这里是返回 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'
    }
});

感谢您的所有回复。

【问题讨论】:

  • 您的代码返回错误“无法更新公司,请重试”。而不是这样做,你为什么不也包括来自对象“err”的信息,而不是丢弃它。它会给你更多关于正在发生的事情的线索。
  • 我建议您打印 company 对象并打印 err 对象。这将使您对出了什么问题有更多的了解。可能数据并没有完全按照您的模型需要。
  • 在您的架构中,students 应声明为类似 students: [{ type : mongoose.Schema.Types.ObjectId,ref : 'users' }] 的数组

标签: node.js mongodb mongoose mean-stack


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我的终端出现了“TypeError: company.students.push is not a function”。
    • 我认为当您在学生变量中保存 req.params.id 时,请尝试将其转换为猫鼬对象 id。喜欢mongoose.Types.ObjectID(req.params.id)
    【解决方案3】:
    你在这里犯了两个错误 1)您的架构类型是 ObjectId 但您正在推送字符串 将字符串转换为 ObjectId : mongoose.Types.ObjectId 2)在学生中存储一个数组,它会变成这样 => var students=[ObjectId('')] 3)现在再次分配给company.students之前,您正在推动 与学生变量相同的 objectId 尝试以下几行
           // var students = [req.params.id];you don't need this line
            company.students.push(req.params.id)
    

    【讨论】:

    • 我得到了这个“TypeError: company.students.push is not a function”
    • 确保学生字段是一个数组 student:[{type: db.Schema.Types.ObjectId, ref: ''}]
    【解决方案4】:

    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 为您提供了非常漂亮的方法来验证不同的事物

    【讨论】:

      猜你喜欢
      • 2020-06-04
      • 2018-05-23
      • 1970-01-01
      • 2020-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      • 2018-07-02
      相关资源
      最近更新 更多