【发布时间】:2019-10-19 12:14:49
【问题描述】:
运行 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() 时,我可以看到已添加完整文档。但是,在猫鼬模型上运行时:
Room.find({}).exec((err,rooms)=>{
console.log(rooms[0].toJSON());
});
我看不到用户子文档,而且我看不到用户字段!似乎是什么问题?
从猫鼬模型记录的 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
}
【问题讨论】:
-
“看不到用户子文档”到底是什么意思?请将您打印到控制台时看到的内容发布出来。
-
@kevinadi 我相应地更新了问题。有什么想法可以引导我朝着正确的方向前进吗?
标签: mongodb typescript mongoose