node.js - Mongoose for var in loop 在子文档中

标签 node.js mongodb for-loop mongoose subdocument

我用 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 子文档的第一个元素。

谢谢

最佳答案

使用索引 for 循环,而不是 forin:

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

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

关于node.js - Mongoose for var in loop 在子文档中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32754659/

相关文章:

java - 无法连接到 mongo 容器

c++ - 如何在 C++ 中使用 for 循环递增两个不同的值

java - 将输入的单词数字(如七)转换为字符(如@)

javascript - 从数组 Javascript 中删除重复项

node.js - 在哪里放置 robots.txt - Nodejs Express 项目

javascript - 使用express.js获取url的查询字符串

node.js - Mongoose 组和计数

javascript - 从 Node + Express API 中提取使用 res.json 发送的信息

node.js - 如何获取protobuf.js以输出枚举字符串而不是整数

mongodb - 使用pymongo选择带有过滤器的随机文档?