Mongoose findOne 转换对象中的数组类型字段

不知名的程序员

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

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 } }

有什么解决方法吗?

whoami - fakeFaceTrueSoul

那是因为你的猫鼬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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Mongoose findOne 返回对象子数组的计数

Mongoose findOne 不适用于数字字段

如何在Mongoose findOne()调用中使用Date对象

使用 findOne() 后如何从 mongoose/mongodb 文档中获取值

Mongoose findOne 總是返回 undefined

mongoose.findOne()返回null

Express - 如何从 Model.findOne() 和 Model.create() mongoose 返回的响应中排除字段

使用 findOne 进行 mongoose 查询时,json 对象的形状是否必须匹配?

如何在array.forEach中的.push之前混杂MongoDB / Mongoose .findOne?

Mongoose 从 model.find 和 model.FindOne 响应中删除了一些数据

如何在 Mongoose 中更新此文檔值?.findOne 然後 .save() 不起作用

findOne mongoose 查询无法正常工作

_id的Mongoose findOne嵌入式文档

Mongoose.findOne返回相同的文档

Mongoose - FindOne 和 Search inside 和 Array

用Mongoose .findOne()验证jwt令牌

即使数据不匹配,在数组中具有嵌套属性的集合文档上的 Mongoose findOne() 也会解析

当我尝试处理 mongoose.findOne 中的错误时,它给了我“未处理的‘错误’事件”

Mongo findOne 在 Array 中

Mongoose.findOne不返回任何内容,为什么?

如何覆盖用于测试的模式上的Mongoose findOne()函数?

函数使用Mongoose findOne返回未定义?

Mongoose findOne 函数返回空/未定义

Mongoose.js findOne返回查询元数据

Mongoose 将 findOne() 结果分配给变量

使用Mongoose FindOne和Bluebird Promises在循环中构建阵列

findOne 与 $push 创建重复的对象

显示findOne的输出:Object对象

猫鼬查询FindOne与数组