Using node.js / express and mongoose (mongodb) and passport. 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:
<%= 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.
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!!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.