【问题标题】:Mongoose for var in loop in subdocumentsMongoose for var in loop 在子文档中
【发布时间】:2023-03-18 02:45:01
【问题描述】:

我用mongoose Schema 创建了这个架构:

socialAccount =  new Schema({
    socialNetwork : { type : String , required : true},
    userid : { type : Number,  required :  true },
    username : String
},{_id : false});
person = new Schema({
    id : { type : Number,  unique : true, required : true , dropDups :  true },
    firstname : String,
    lastname : String,
    socialAccounts : [socialAccount],
    updated : { type : Date, default : Date.now },
    enable : { type : Boolean , default : true },       
});

当我使用findOne 方法获取数据时,结果如下所示(在console.log() 中):

{ 
  id: 1,
  firstname: 'example name',
  lastname: 'example last',
  enable: true,
  updated: Thu Sep 24 2015 09:40:17 GMT+0330 (IRST),
  socialAccounts: 
   [ { socialNetwork: 'instagram',
       userid: 1234567,
       username: 'example' } ] }

所以,当我想用​​for var in 循环结构和查看数据console.log() 迭代子文档socialAccounts 时,它返回一些其他对象和函数并且只有第一个是子文档对象。
如何使用这种 for 循环迭代方法仅获取 socialAccounts 子文档的第一个元素。

谢谢

【问题讨论】:

  • 我认为 Person.findOne 返回一个 bson 文件,您可能希望 JSON.parse(JSON.stringify()) 将该文件设为普通数组对象
  • 谢谢,这种方式也可以。但我认为代码越少越好,所以我想使用@qqilihq 方法。

标签: node.js mongodb for-loop mongoose subdocument


【解决方案1】:

使用带索引的 for 循环,而不是 for ... in:

for (let i = 0; i < socialAccounts.length; i++) {
    var currentAccount = socialAccounts[i];
}

for ... in 循环将枚举您注意到的其他对象属性,不应将其用于数组。见this问答。

【讨论】:

  • 如何使用 for ... in 枚举对象属性?
【解决方案2】:

试试

.findOne(...() => {})

它对我有用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2022-11-20
    • 2011-04-12
    • 2018-09-16
    • 1970-01-01
    • 2020-07-16
    相关资源
    最近更新 更多