猫鼬findOne转换对象中的Array type字段

时间:2020-05-04 21:36:57

标签: node.js mongodb mongoose mongodb-query

我一直在构建聊天应用程序,并且正在用模式存储用户

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" : "doe@gmail.com",
 "__v" : 0,
 "contacts" : [
    {
        "_id" : ObjectId("5eb07958b0315c6303505f74"),
        "contactUserId" : "RHOCbyCtvjQfFzFukxiwS9wV1ly1"
    },
    {
        "_id" : ObjectId("5eb07e4eff338702ba455c8a"),
        "contactUserId" : "tGCkdHh55UgkG8AW0Ab6S9guwcF3"
    }
 ]

}

但是当我尝试使用猫鼬findOne时,它将使用联系人字段作为对象来检索用户:

{ _id: '49Ff7aRn4baPuTVFefQLulbMIeE2',
 username: 'john',
 email: 'doe@gmail.com',
 __v: 0,
 contacts:
  { '0':
     { _id: 5eb07958b0315c6303505f74,
       contactUserId: 'RHOCbyCtvjQfFzFukxiwS9wV1ly1' },
    '1':
     { _id: 5eb07e4eff338702ba455c8a,
       contactUserId: 'tGCkdHh55UgkG8AW0Ab6S9guwcF3' },
    _id: 5eb086555cbcb03801350d76 } }

有什么解决方法吗?

2 个答案:

答案 0 :(得分:3)

那是因为您的猫鼬UserSchema

将Object类型的contacts: { type: ContactSchema }更改为Object类型数组的contacts: [ContactSchema],如下所示:

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返回文档。

答案 1 :(得分:0)

    commands.CommandError: Diagnostics found a compilation environment issue:

    Could not find <Python.h>. This could mean the following:
      * You're on Ubuntu and haven't run `apt-get install python-dev`.
      * You're on RHEL/Fedora and haven't run `yum install python-devel` or
        `dnf install python-devel` (make sure you also have redhat-rpm-config
        installed)
      * You're on Mac OS X and the usual Python framework was somehow corrupted
        (check your environment variables or try re-installing?)
      * You're on Windows and your Python installation was somehow corrupted
        (check your environment variables or try re-installing?)

联系人应如上所述而不是

cproton_wrap.c:150:21: fatal error: Python.h: No such file or directory
      # include <Python.h>
                          ^
compilation terminated.     
error: command 'gcc' failed with exit status 1