javascript - Mongoose 保存子文档数组

标签 javascript node.js mongodb express mongoose

我正在努力保存子文档数组。只是不会保存:

前端发送一个包含标题数组的 Day 对象,每个标题可以包含一个内容数组(这是一个 mongoose 模式)。

var DaySchema = mongoose.Schema({
date: Date,
startTime: Date,
endTime: Date,
title: String,
order: Number,
description: String,
cohort: {
    type: objId,
    ref: 'cohort'
},
instructors: [{
    type: objId,
    ref: 'instructor'
}],
headings: [{
    title: String,
    subTitle: String,
    content: [{
        type:objId,
        ref: 'content'
    }]
}]
});


var ContentSchema = mongoose.Schema({
title: String,
description: String,
contentUrl: String,
dueDate: Date,
dateAssigned: Date,
downloadUrl: String
});

这是我用来 PUT 和 POST 一天的代码,以及相关的 Content 对象。除了保存内容外,一切正常。当我查看 mongo shell 时,标题下的每个内容字段如下所示:

content: []

有什么想法吗?

exports.putdaycontent = function (req, res) {

var dayId = req.params.dayId;
var headings = req.body.headings;
var day = req.body;

var updateDay = function () {
    Day.update({_id: dayId}, day, {new: true, upsert: true}, function (err, day) {
        if (err)
            error.databaseError(req, res, err);

        res.send(day);
    });
};

if (headings) {
    for (var x = 0; x < headings.length; x++) {
        var h = headings[x];

        if (h.content) {
            for (var y = 0; y < h.content.length; y++) {
                var c = h.content[y];

                //If existing content update it
                if (c._id && c._id.length > 0) {
                    Content.update({_id: c._id}, c, {new: true,upsert: true}, function (err, content) {

                    });
                } else {
                    var content = new Content(c);
                    h.content[y] = content;
                }

            }
        }
    }
    day.headings = headings;
    updateDay();

} else {
    updateDay();
}


};

exports.postdaycontent = function (req, res) {

var headings = req.body.headings;
var day = req.body;
var cohortId = day.cohort._id;

var postDay = function () {
    var d = new Day(day);
    console.log("CONTENT DAYS:",d);
    d.save(function(err, newDay) {
       if (err)
           error.databaseError(req, res, err);

        Cohort.findOneAndUpdate({_id: cohortId}, {$push: {days: newDay}}, {upsert: true}, function(err, newCohort) {
            res.send({msg:"Successfully saved day to cohort"});
        });
    });
};

if (headings) {
    for (var x = 0; x < headings.length; x++) {
        var h = headings[x];

        if (h.content) {
            for (var y = 0; y < h.content.length; y++) {
                var c = h.content[y];

                var content = new Content(c);
                h.content[y] = content;
                console.log("CONTENT:",content);

            }
        }
    }
    day.headings = headings;
} 

postDay();
};

最佳答案

这是我几天前在 2015 年 6 月 22 日遇到的问题。这是我在 github https://github.com/Automattic/mongoose/issues/3093 上提出的问题的链接。 .


现在您的问题有两种解决方案。

  1. use .set() explicitly whenever you're modifying an array index

例如:

doc.someArray.set('3', 'changed');
doc.save();

这里的数组名为someArray正在更改,因此我们需要使用 array.set 方法更改它。

缺点: 数组的每个元素都需要使用 array.set() 设置,例如,数组中的 5 个元素发生变化,您需要使用 array.set 设置所有这些元素.


2. 将数组标记为已修改,然后保存。

例如:

doc.array[3] = 'changed';
doc.markModified('array');

这是另一种方式,当您不能显式调用 array.set 时方法。例如:在我的例子中,我使用 loadash 合并文档并保存它,我无法使用 array.set ,因此我使用了array.markModified .

好处: 您不需要像上面那样设置数组中的每个元素 array.set方法。

缺点:

对于每个数组,您需要在保存前将其标记为已修改。 例如:如果您的文档中有 10 个数组,您需要在保存之前将它们全部标记为已修改:喜欢,

 doc.markModified('array1');
 doc.markModified('array2');
 doc.markModified('array3');


mongoose 中仍然没有将多个数组标记为已修改的选项。我已在上面分享的链接中请求此功能。

所以这会是这样的:

profile.markAllModified(['arrayFirst','arraySecond','arrayThird','arrayFourth']);

已添加到 mongoose 的里程碑 4.0.7,希望我们能尽快看到此功能。

关于javascript - Mongoose 保存子文档数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31236111/

相关文章:

Javascript、Web Audio API、Oscillator.stop() 有烦人的结束滴答声

javascript - 如果找不到替换信,请保留原信

node.js - 从 NodeJS 启动和停止 Python 脚本?

mongodb - 匹配数组内的多个条件

javascript - window.location.href 和 top.location.href 的区别

php - AJAX 和 MVC 混合

node.js - NodeJS - 如何安全地存储数据库的 ip、用户名和密码?

javascript - 使函数的行为类似于实例化的 EventEmitter

mongodb - 在 Worker 的帮助下从 Spark 读取巨大的 MongoDB 集合

mongodb - 使用 Backbone.js 的投票系统