Mongoose findOne转换对象中的Array类型字段。

问题描述 投票:0回答:1

我一直在建立一个聊天程序,我用一个模式来存储用户。

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,
},
});

问题是,当我试图在mongo shell中用findOne查找用户时,它用联系人数组检索到了用户。

{
 "_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 } }

有什么办法可以解决这个问题吗?

javascript node.js mongodb mongoose
1个回答
3
投票

那是因为你的mongoose UserSchema :

变化 contacts: { type: ContactSchema } 类型的对象到 contacts: [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中原样返回文档。


0
投票
const UserSchema = new mongoose.Schema({
_id: {
type: String,
required: true,
},
email: {
 type: String,
 required: true,
},
username: {
 type: String,
 required: true,
},
contacts: [ContactSchema]
});

应该像上面一样提到contacts,而不是

const UserSchema = new mongoose.Schema({
_id: {
type: String,
required: true,
},
email: {
 type: String,
 required: true,
},
username: {
 type: String,
 required: true,
},
contacts: {
 type: ContactSchema,
},
});
© www.soinside.com 2019 - 2024. All rights reserved.