草庐IT

node.js - Mongoose 不会将嵌套对象保存在另一个嵌套对象中

coder 2023-10-31 原文

通常在mongoose中保存嵌套的对象,通过父亲的调用方法save,但是如果我们有两层约定,祖父,父亲[nested],儿子[nested],儿子是不会通过父亲的调用方法save来保存的.

祖父 -> 组

var schema = new mongoose.Schema({
   name: String,
   days:[mongoose.Schema.Types.Day],
});

module.exports = mongoose.model('Group', schema);

父亲 -> 日

var schema = new mongoose.Schema({
   _id: Number,
   matches:[mongoose.Schema.Types.Match]
});
module.exports = mongoose.model('Day', schema);

儿子 -> 匹配

var schema = new mongoose.Schema({
  team1: {
    type: Schema.ObjectId,
    ref:'Team'
  },
  team2: {
    type: Schema.ObjectId,
    ref: 'Team'
  },
  score: [Number]
});

module.exports = mongoose.model('Match', schema);

在路由(“matches.js”)中,我尝试保存组联合天和匹配。

Group.findById(groupId).exec(
        function(err, group){
        var match = new Match();
        var day = group.days[dayNumber-1];
        day.matches.push(
            match
        );
        group.save(function(err){
            console.log("success");
            console.log("group in matches.js:"+group);
            res.redirect("/tournaments/"+tournamentId+"/groups/"+groupId+"/days/"+dayNumber);
        });
     });

在重定向中,我再次打印“组”,匹配消失。

app.get('/tournaments/:tournamentId/groups/:groupId/days/:dayNumber', function (req, res) {
    groupId = req.params.groupId;
    dayNumber =  req.params.dayNumber;
    Group.findById(groupId, function (err, group) {
        console.log("group in days.js:"+group);
        res.render('days/show', {
            title: 'Days',
            group:  group,
            day:group.days[dayNumber-1],
            tournamentId: req.params.tournamentId
        });
    });
});

控制台日志打印:

new match
success
group in matches.js:{ __v: 7,
  _id: 53a3ee54dfe793bd9a20c6ab,
  name: 'gruppo sdirubbo',
  days: [ { matches: [Object], _id: 1 } ] }
GET /tournaments/539f0185ea17e46e73be937b/groups/53a3ee54dfe793bd9a20c6ab/days/1/newMatch 302 4ms - 208b
group in days.js:{ __v: 7,
  _id: 53a3ee54dfe793bd9a20c6ab,
  name: 'gruppo sdirubbo',
  days: [ { matches: [], _id: 1 } ] }

最佳答案

mongoose.Schema.Types.Daymongoose.Schema.Types.Match 未定义,因此引用它们的那些数组字段最终以 Mixed 类型,除非您明确标记它们已修改,否则它们不会保存。

您需要使这些模式在模型定义之间可用,然后在您的定义中使用它们。例如:

var matchSchema = new mongoose.Schema({
  team1: {
    type: Schema.ObjectId,
    ref:'Team'
  },
  team2: {
    type: Schema.ObjectId,
    ref: 'Team'
  },
  score: [Number]
});

var daySchema = new mongoose.Schema({
   _id: Number,
   matches:[matchSchema]
});

var groupSchema = new mongoose.Schema({
   name: String,
   days:[daySchema],
});

关于node.js - Mongoose 不会将嵌套对象保存在另一个嵌套对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24328057/

有关node.js - Mongoose 不会将嵌套对象保存在另一个嵌套对象中的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  3. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  4. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  5. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  6. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  7. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  8. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  9. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  10. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

随机推荐