简体   繁体   English

无法使用javascript和mongodb将json对象推入数组

[英]Can't push a json object into array using javascript and mongodb

I have a problem pushing into my Student model data and its schema looks as below: 我在推送学生模型数据时遇到问题,其架构如下所示:

var StudentSchema = new Schema({
    firstName: {
        type: String,
        trim: true,
        default: ''
        //validate: [validateLocalStrategyProperty, 'Please fill in your first name']
    },
    lastName: {
        type: String,
        trim: true,
        default: ''
        //validate: [validateLocalStrategyProperty, 'Please fill in your last name']
    },
    worksnap: {
        user: {
            type: Object
        },
        timeEntries : [],
    },
    timeEntries : []
});

While my javascript code for pushing items looks like this: 虽然我推送项目的javascript代码如下所示:

Student.findOne({
            'worksnap.user.user_id': item.user_id[0]
        })
        .populate('user')
        .exec(function (err, student) {
            if (err) {
                throw err;
            }
            //student.timeEntries.push(item); // this works
            student.worksnap.timeEntries.push(item); // this does not work
            student.save(function (err) {
                if (err) {
                    //return res.status(400).send({
                    //    message: errorHandler.getErrorMessage(err)
                    //});
                } else {
                    console.log('item inserted...');
                }
            });

        });

As you can see, if I use timeEntries array outside the worksnap object it works fine, it inserts the item as object into that array... I just don't know why it is not working the same being inside worksnap object. 正如你所看到的,如果我在worksnap对象之外使用timeEntries数组它工作正常,它将项目作为对象插入到该数组中......我只是不知道为什么它在worknap对象中不起作用。

Is there any other option that I can add json objects into an array type in mongo 是否有任何其他选项可以将json对象添加到mongo中的数组类型中

Thanks 谢谢

Use .lean() 使用.lean()

Documents returned from queries with the lean option enabled are plain JavaScript objects, not MongooseDocuments . 从启用了精益选项的查询返回的文档是纯JavaScript对象,而不是MongooseDocuments They have no save method, getters/setters or other Mongoose magic applied. 他们没有保存方法,getter / setter或其他Mongoose魔法应用。

 Student.findOne({ 'worksnap.user.user_id': item.user_id[0] }) .populate('user') .lean()//-----Added! .exec(function(err, student) { if (err) { throw err; } //student.timeEntries.push(item); // this works student.worksnap.timeEntries.push(item); // this does not work student.save(function(err) { if (err) { //return res.status(400).send({ // message: errorHandler.getErrorMessage(err) //}); } else { console.log('item inserted...'); } }); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM