首页 > 解决方案 > Mongoose - 子文档数组问题

问题描述

我有一个“公司”模型,它有多个“房间”。

我可以毫无问题地创建房间,而且他们有一个返回公司的链接。

问题是当我得到 Company 时,Rooms 数组没有项目。

我可以看到房间存在并且有一个返回公司的链接:

{
    "RoomType": 0,
    "AllowedRoomRoles": [
        "5f999f4f542eed1b8fce5fa9"
    ],
    "Enabled": true,
    "_id": "5fb677b453658c7070bf9433",
    "RoomName": "Martins Room 2",
    "RoomPin": "0001",
    "Company": "5fad553db19ca100161a0d8f",
    "__v": 0
}

但是,当我这样做时: var company = await CompanyModel.findById('5fad553db19ca100161a0d8f');

我让 Company 回来了,但 Rooms 数组中没有任何项目。

这是我的模型:

//Room Schema:

const roomSchema = new Schema({
RoomPin: String,
  RoomName: String,
  RoomType: { type: RoomType, default: RoomType.MeetingRoom } ,
  Company: {type: Schema.Types.ObjectId, ref: 'CompanySchema'},
  AllowedRoomRoles: [{type: Schema.Types.ObjectId, ref: 'RoomRoleSchema'}],
  Enabled: { type: Boolean, default: true },
}, {
    collection: "room"
})

//Company Schema:

const companySchema = new Schema({
  CompanyName: { type: String, required: true },
  CompanyLogo: { type: String, required: true },
  Enabled: { type: Boolean, default: true },
  CompanyIdentifier: { type: String, required: true },
  CompanyWebsite: { type: String, required: true },
  Rooms: [{type: Schema.Types.ObjectId, ref: 'RoomSchema'}],
}, {
    collection: "company"
})

Minor update:

Seems doing it this way around is fine?

```var rooms = await RoomModel.find({'Company': company._id.toString() });

标签: mongodbmongoose

解决方案


推荐阅读