javascript - 将自定义对象的 Mongoose PUT 实现到复杂模式中时出现问题

标签 javascript node.js mongodb express mongoose

我将分解问题以确保我已经很好地解释了它。

我的网络应用程序正在使用 MEAN.js,在本例中,我在 mongoose 服务器端 Controller 中实现更新功能。 使用此架构:

客户端 Angular Controller 代码工作正常,它向我发送正确的对象以将其插入到 mongodb

我有一个自定义对象数组,由数据库中的其他相关架构对象组成,它表示引用任务对象的更新列表、Taskstate 对象的更改以及更新发生的时间。

 tupdates:[{
        task:{
          type: Schema.ObjectId,
          ref: 'Task'
        },
        tstate:{
          type: Schema.ObjectId,
            ref: 'Tstate'
        },
        startedat: Date,
        stoppedat: Date,
        updatedby:{
            type: Schema.ObjectId,
            ref: 'User'
        },
    }]

我实现了一个函数,该函数将循环遍历 req 对象中的数组,并为数组中的每个更新创建自定义对象,最后将其插入数据库中。 服务器端 Mongoose Controller

var mongoose = require('mongoose'),
Job = mongoose.model('Job');
    exports.update = function(req, res){
    var job = req.job;

    //check for updates
    if(req.body.tupdates.length>0){
    for (var j=0; j<req.body.tupdates.length; j++){

        var theobj = req.body.tupdates[j];
        var tupdate = ({
           task : theobj.task._id,
            tstate: theobj.tstate._id
        });
job.tupdates.push(tupdate);
        }
    }
    job.save(function(err){
        if(err){
            return res.status(400).send({
                message: getErrorMessage(err)
            });
        }else{
            res.json(job);
        }
    });
};enter code here

数据保留在数据库中,问题是为 req 数组中的每个更新插入了一个我没有引用的带有 ObjectID 的附加 _id 值,如下所示:

db.jobs.find()
{ "_id" : ObjectId("56eff14d4b343c7f0a71f33c"), "creator" : ObjectId("55ddd115a2904424680263a0"), "title" : "Job1", "tupdates" : [ { "task" : ObjectId("567a9c4b90f3ccd10b0e7099"), "tstate" : ObjectId("5693bb0f804936f167fe9ec2"), *"_id" : ObjectId("56eff38e095a2fa41312d876")*} ]}

我添加了这些星号来指示带有 ObjectId 引用的 _id 值,该值被添加到我在服务器端 Controller 中创建的对象中,每次我对同一对象进行更新时,问题仍然存在。它稍后会创建 500 个错误,并且必须忽略该函数才能在生产中正常工作,我感谢您的帮助,认为这是我需要进行的 java 脚本调整。

最佳答案

默认情况下,如果数组元素是对象,mongoose 会将 _id 字段添加到数组元素中。 只需将 _id: false 添加到您的架构中即可:

    tupdates:[{
        _id: false,
        task:{
          type: Schema.ObjectId,
          ref: 'Task'
        },
        tstate:{
          type: Schema.ObjectId,
            ref: 'Tstate'
        },
        startedat: Date,
        stoppedat: Date,
        updatedby:{
            type: Schema.ObjectId,
            ref: 'User'
        },
    }]

关于javascript - 将自定义对象的 Mongoose PUT 实现到复杂模式中时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36132500/

相关文章:

javascript - 自执行箭头函数

javascript - Socket.io 分别与每个用户合作

angularjs - 运行 yo 意味着 js 挂起

javascript - 并行运行 Express 服务和 Angular 6 应用程序

angularjs - 不确定如何使用 meanjs 限制路由

ruby-on-rails - Mongoid 相当于 create_with

javascript - 尝试检查 firebase firestore 文档中的某个字段,但苦于其背后的逻辑

javascript - 从文本中消除特定模式

javascript - 如何在 Angular js中的ng-model-options中去抖后运行函数

node.js - 使用 Pushstate 和 NodeJS