M2s*_*2sh 5 for-loop mongoose mongodb node.js 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 },
});
Run Code Online (Sandbox Code Playgroud)
当我使用findOne方法获取数据时,结果如下所示(in 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' } ] }
Run Code Online (Sandbox Code Playgroud)
那么,当我想在循环结构和视图数据的子文档socialAccounts上迭代时,它返回一些其他对象和函数,只有第一个是子文档对象.
我怎样才能获得这个for循环迭代方法的子文档的第一个元素.for var inconsole.log()socialAccounts
谢谢
使用索引for循环,而不是for... in:
for (var i = 0; i < socialAccounts.length; i++) {
var currentAccount = socialAccounts[i];
}
Run Code Online (Sandbox Code Playgroud)
该for... in你发现,不应该被用于阵列循环将列举其他对象特性.看到这个问题和答案.