【发布时间】: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