草庐IT

mongodb - Mongoose 查询不显示子文档

coder 2023-11-05 原文

运行 find() 时我无法让 mongoose 显示子文档,而它在 mongodb shell 中显示得很好。

子文档应该根据我的模式嵌入,而不是引用 objectId,所以我不应该运行任何黑魔法巫术来显示我的数据。

const UserSchema = new mongoose.Schema({
  username: String;
  xp: Number;
  //etc.
});

const RoomSchema = new mongoose.Schema({
  timestamp: { type: Date, default: Date.now },
  status: { type: String, enum: ["pending", "ongoing", "completed"]},
  players: {
    type: [{
      points: { type: Number, default: 0 },
      position: String,
      user: UserSchema
    }],
    maxlength:2
  }
});

添加新房间后:

let room = new Room(coreObj);
room.players.push({
  points: 0,
  position: 'blue',
  user: userObj //where userObj is a result of running findById on User model
});

它在 mongo shell 中显示得很好,当运行 db.rooms.find({}).pretty() 时,我可以看到已添加完整文档。但是,在 Mongoose 模型上运行时:

Room.find({}).exec((err,rooms)=>{
  console.log(rooms[0].toJSON()); 
});

我没有看到用户子文档,而且我完全看不到用户字段!似乎是什么问题?

从 mongoose 模型记录 json:

{
    "status": "pending",
    "_id": "5cf5a25c050db208641a2076",
    "timestamp": "2019-06-03T22:42:36.946Z",
    "players": [
        {
            "points": 0,
            "_id": "5cf5a25c050db208641a2077",
            "position": "blue"
        }
    ],
    "__v": 0
}

来自 mongo shell 的 json:

{
        "_id" : ObjectId("5cf5a25c050db208641a2076"),
        "status" : "pending",
        "timestamp" : ISODate("2019-06-03T22:42:36.946Z"),
        "players" : [
                {
                        "points" : 0,
                        "_id" : ObjectId("5cf5a25c050db208641a2077"),
                        "position" : "blue",
                        "user" : {
                                "xp" : 0,
                                "_id" : ObjectId("5cf2da91a45db837b8061270"),
                                "username" : "bogdan_zvonko",
                                "__v" : 0
                        }
                }
        ],
        "__v" : 0
}

最佳答案

考虑到最佳实践,我认为在 RoomSchema 中引用 UserSchema 会更合适。像这样的东西:

...
user: {
   type: Schema.Types.ObjectId,
   ref: 'UserSchema'
}

然后您将在该字段中存储 user._id

这样,如果用户被修改,您的 RoomSchema 将始终引用正确的信息。然后,您可以使用 Mongoose 的 populate

获取用户

关于mongodb - Mongoose 查询不显示子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56435859/

有关mongodb - Mongoose 查询不显示子文档的更多相关文章

  1. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  2. 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

  3. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  4. ruby-on-rails - 使用 Sublime Text 3 突出显示 HTML 背景语法中的 ERB? - 2

    所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择

  5. ruby-on-rails - link_to 不显示任何 rails - 2

    我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article

  6. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

  7. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  8. ruby-on-rails - 复数 for fields_for has_many 关联未显示在 View 中 - 2

    目前,Itembelongs_toCompany和has_manyItemVariants。我正在尝试使用嵌套的fields_for通过Item表单添加ItemVariant字段,但是使用:item_variants不显示该表单。只有当我使用单数时才会显示。我检查了我的关联,它们似乎是正确的,这可能与嵌套在公司下的项目有关,还是我遗漏了其他东西?提前致谢。注意:下面的代码片段中省略了不相关的代码。编辑:不知道这是否相关,但我正在使用CanCan进行身份验证。routes.rbresources:companiesdoresources:itemsenditem.rbclassItemi

  9. ruby-on-rails - 在 Flash 警报 Rails 3 中显示错误消息 - 2

    如果我在模型中设置验证消息validates:name,:presence=>{:message=>'Thenamecantbeblank.'}我如何让该消息显示在闪光警报中,这是我迄今为止尝试过的方法defcreate@message=Message.new(params[:message])if@message.valid?ContactMailer.send_mail(@message).deliverredirect_to(root_path,:notice=>"Thanksforyourmessage,Iwillbeintouchsoon")elseflash[:error]

  10. sql - 查询忽略时间戳日期的时间范围 - 2

    我正在尝试查询我的Rails数据库(Postgres)中的购买表,我想查询时间范围。例如,我想知道在所有日期的下午2点到3点之间进行了多少次购买。此表中有一个created_at列,但我不知道如何在不搜索特定日期的情况下完成此操作。我试过:Purchases.where("created_atBETWEEN?and?",Time.now-1.hour,Time.now)但这最终只会搜索今天与那些时间的日期。 最佳答案 您需要使用PostgreSQL'sdate_part/extractfunction从created_at中提取小时

随机推荐