运行find()时,我无法让猫鼬显示子文档,尽管它在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
});
运行db.rooms.find({})。pretty()时,它在mongo shell中显示很好,我可以看到已添加了完整文档。但是,在猫鼬模型上运行时:
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
}
答案 0 :(得分:1)
牢记最佳实践,我认为在UserSchema
中引用RoomSchema
更合适。像这样:
...
user: {
type: Schema.Types.ObjectId,
ref: 'UserSchema'
}
然后,您将user._id
存储在该字段中。
这样,如果修改了用户,则您的RoomSchema
总是引用正确的信息。然后,您可以使用Mongoose的populate
答案 1 :(得分:0)
我不确定您为什么看不到子子文档,但是此代码示例为我正确打印了该子文档。该示例最初发布在https://mongoosejs.com/docs/subdocs.html中,但进行了稍微修改以包含子子文档,因此它看起来类似于您的代码:
var grandChildSchema = new mongoose.Schema({ name: 'string' });
var childSchema = new mongoose.Schema({ name: 'string', grandChild: grandChildSchema });
var parentSchema = new mongoose.Schema({ children: [childSchema] });
var Parent = mongoose.model('Parent', parentSchema);
var parent = new Parent({
children: [
{ name: 'Matt', grandChild: {name: 'Matt Jr'} },
{ name: 'Sarah', grandChild: {name: 'Sarah Jr'} }
]
})
parent.save(function() {
Parent.find().exec(function(err, res) {
console.log(JSON.stringify(res[0]))
mongoose.connection.close()
})
});
执行此代码会导致:
{
"_id": "5cf7096408b1f54151ef907c",
"children": [
{
"_id": "5cf7096408b1f54151ef907f",
"name": "Matt",
"grandChild": {
"_id": "5cf7096408b1f54151ef9080",
"name": "Matt Jr"
}
},
{
"_id": "5cf7096408b1f54151ef907d",
"name": "Sarah",
"grandChild": {
"_id": "5cf7096408b1f54151ef907e",
"name": "Sarah Jr"
}
}
],
"__v": 0
}
这是使用Mongoose 5.5.12测试的。
请注意,我使用JSON.stringify()
来打印文档,而不是使用Mongoose的toJSON()
。