简体   繁体   English

无法查询从Mongodb返回的类似数组的对象

[英]cannot query array-like object returned from Mongodb

Using node.js / express and mongoose (mongodb) and passport. 使用node.js / express和mongoose(mongodb)和护照。 I am having trouble getting to the key/value pairs of the returned array- like object. 我在获取类似返回的数组的键/值对时遇到麻烦。 user model: 用户模型:

{ 
 local : {
   email     : String,
   password  : String
},
 skills : {
  skill     : String,
  level     : Number
 }
}

I can add new skills to the user like this: Works exactly as intended 我可以像这样向用户添加新技能:完全按预期工作

app.post( '/addskill', function ( req, res ) {
    var newskill = {skill : req.body.skill,  level : req.body.level};
    User.findByIdAndUpdate( req.user.id,
     { $push: { skills: newskill }}, 
     function (err, user ) {
      res.redirect('/profile');
    });
});

I can easily access the email and password strings in my ejs file like this: 我可以像这样轻松地访问我的ejs文件中的电子邮件和密码字符串:

<%= user.local.email %>
<%= user.local.password %>

When I query the db with 当我查询数据库

user.skills

I can get all the skills in this format: 我可以通过以下格式获得所有技能:

[ { skill: 'qwe', level: 1 }, { skill: 'html', level: 1 }, { skill: 'python', level: 4 } ]

Again, exactly what I am looking for. 再次,正是我要的东西。 What I want to do now is create a table listing the skills and levels. 我现在想做的是创建一张列出技能和水平的表格。

None of the array methods seem to work I tried in the ejs template file. 我在ejs模板文件中尝试过的所有数组方法似乎都不起作用。

user.skills.forEach()  -- not working 'user' is null
user.forEach --  works to create a list of users.
user.skills[0].skill  -- not working
user.skills[i].skill -- in var loop, not working

here is the error message: 这是错误消息:

Object [ { skill: 'qwe', level: 1 }, { skill: 'html', level: 1 }, 
{ skill: 'python', level: 4 } ] has no method 'forEach' at eval ...

So my question really is: How can I access the key-value pairs in the this collection (array?) 所以我的问题确实是:如何访问此集合中的键值对(数组?)

Thanks!! 谢谢!!

so the solution here is to define an array in your mongoose model: 所以这里的解决方案是在猫鼬模型中定义一个数组:

All I had to do is add [] to the 'skill' section: 我要做的就是将[]添加到“技能”部分:

{ 
 local : {
   email     : String,
   password  : String
},
 skills : [{
  skill     : String,
  level     : Number
 }]
}

now all the array methods work!! 现在所有的数组方法都可以使用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM