我一直在构建一个聊天应用程序,我正在用一个模式存储用户
const UserSchema = new mongoose.Schema({
_id: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
username: {
type: String,
required: true,
},
contacts: {
type: ContactSchema,
},
});
和 ContactSchema 作为
const ContactSchema = new Schema({
contactUserId: {
type: String,
required: true,
},
});
问题是,当我尝试使用 findOne 在 mongo shell 中查找用户时,它使用联系人数组检索用户:
{
"_id" : "49Ff7aRn4baPuTVFefQLulbMIeE2",
"username" : "john",
"email" : "[email protected]",
"__v" : 0,
"contacts" : [
{
"_id" : ObjectId("5eb07958b0315c6303505f74"),
"contactUserId" : "RHOCbyCtvjQfFzFukxiwS9wV1ly1"
},
{
"_id" : ObjectId("5eb07e4eff338702ba455c8a"),
"contactUserId" : "tGCkdHh55UgkG8AW0Ab6S9guwcF3"
}
]
}
但是当我尝试使用 mongoose findOne 时,它以联系人字段作为对象检索用户:
{ _id: '49Ff7aRn4baPuTVFefQLulbMIeE2',
username: 'john',
email: '[email protected]',
__v: 0,
contacts:
{ '0':
{ _id: 5eb07958b0315c6303505f74,
contactUserId: 'RHOCbyCtvjQfFzFukxiwS9wV1ly1' },
'1':
{ _id: 5eb07e4eff338702ba455c8a,
contactUserId: 'tGCkdHh55UgkG8AW0Ab6S9guwcF3' },
_id: 5eb086555cbcb03801350d76 } }
有什么解决方法吗?
那是因为你的猫鼬UserSchema
:
contacts: { type: ContactSchema }
将 Objectcontacts: [ContactSchema]
类型更改为Objects 类型数组,如下所示:
const UserSchema = new mongoose.Schema({
_id: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
username: {
type: String,
required: true,
},
contacts: [ContactSchema],
});
在 mongo shell 上,由于您没有任何转换,因此非常简单并按原样从 DB 返回文档。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句