提前感谢您抽出宝贵时间。
我正在构建一个使用 Mongoose 作为我的数据库的聊天应用程序。 我正在实现加载用户所在的每个聊天室的最新消息的功能,但它的行为很奇怪。
这是我的用户模型:
const UserSchema = new Schema({
email: String,
password: String,
rooms: [{ type: Schema.Types.ObjectId, ref: "Room" }],
contacts: [{
customName: String,
_contact: { type: Schema.Types.ObjectId, ref: "User" }
}],
});
module.exports = mongoose.model('User', UserSchema);
如您所见,我在用户中嵌入了房间。每次用户与另一个用户创建房间时,它都会在房间集合中创建并插入到两个用户的房间嵌入文档中。
接下来,这是我的房间模型:
const RoomSchema = new Schema({
name: String,
members: [{ type: Schema.Types.ObjectId, ref: "User" }],
messages: [{ type: Schema.Types.ObjectId, ref: "Message" }]
});
module.exports = mongoose.model('Room', RoomSchema);
所以房间包含消息和房间的成员。 这是消息模型:
const MessageSchema = new Schema({
body: String,
from: { type: Schema.Types.ObjectId, ref: "User" },
});
module.exports = mongoose.model('Message', MessageSchema);
当我用房间和房间的消息填充用户时会发生奇怪的行为。
这是我的人口:
user = await User.findById(_id).populate([
{
path: 'rooms',
select: 'messages members name',
populate: [
{
path: 'messages',
select: 'body from',
options: {
limit: 1,
sort: { _id: -1 },
},
populate: {
path: 'from',
select: 'email'
}
},
{
path: 'members',
select: 'email',
},
]
},
{
path: 'contacts',
select: 'customName _contact',
populate: {
path: '_contact',
select: 'email'
}
}])
从这个填充用户的房间返回的是:
rooms: [
{
members: [Array],
messages: [Array],
_id: 60e0d0bad7b0fe927c9df4a9,
name: 'Conversation between 60e084edf890b996ecc19eb6 and 60e089147535536c482a0c50'
},
{
members: [Array],
messages: [],
_id: 60e0d1a243e6869a38664bef,
name: 'Conversation between 60e084edf890b996ecc19eb6 and 60e084d9f890b996ecc19eb5'
},
{
members: [Array],
messages: [Array],
_id: 60e1df592252c64b78f6338e,
name: 'Conversation between 60e084edf890b996ecc19eb6 and 60e0e83d43e6869a38664bf2'
}
],
如您所见,第二个房间尚未填充消息,它返回一个空数组。 而且我当然知道对话有消息,因为最奇怪的是,如果我与房间的其他成员进行相同的填充,它会成功返回消息。但是对于同一个用户,它可能会在另一个不相关的房间失败(返回空消息数组)。
所以,我不知道这是一个错误,还是我做错了什么,我看不到。
我希望得到任何帮助。
非常感谢!