i try push object array in mongoose, whenever it, puts length this(mongoose, attribute schoolcomment @ bottom), using mlab.com database.
{ "_id": { "$oid": "58e17ee3e24dfb1f70d76460" }, "schoolname": "koc universitesi", "schoolilce": "sariyer", "schoolsehir": "istanbul", "schoolid": 981299, "__v": 5, "schoolcomments": [ 3 ] }
this code in node js (the comments not appearing in html because of reason)
app.post('/comment', function(req, res){ if(req.session.user && req.session){ user.findone({email: req.session.user.email}, function(err, user){ if(err) { res.send('error'); } if(user){ if(req.session.user.password === user.password){ var thisid = user.userid; universite.findone({schoolname: req.body.collegename}, function(err, college){ if(err) res.send('error'); if(college){ college.set({schoolcomments: college.schoolcomments.push({thisid: req.body.comment})}).save(function(err){ if(err){ res.render('errors', {error:'error'}); }else{ res.locals.college = college; res.locals.user = user; res.render('universiteinfouser'); } }); } }); }else{ res.render('login', {}); } } }); } });
and html dom form it. comments not appearing because of reasons.
<form onkeypress="enterpress();" action="/comment" method="post"> <textarea maxlength="100" style="font-size: 25px;" name="comment" rows="3" cols="50" placeholder="yorumunuzu yazin..."></textarea><br> <input style="display: none; visibility: hidden;" type="text" name="collegename" value="<%=college.schoolname%>"></input> <button type="submit" name="commentsubmit">comment submit</button> </form> <div class="usercommentdisplay"> <ul> <%college.schoolcomments.foreach(function(item, i){%> <%var k = college.schoolcomments[i]%> <%for(key in k){%> <%if(key === user.userid){%> <li><%=k[key]%> same</li> <%}else{%> <li><%=k[key]%></li> <%}%> <%}%> <%})%> </ul> </div>
you may want use findoneandupdate
, build comment item dynamically (to set dynamic field name) :
var item = {}; item[user.userid] = req.body.comment; universite.findoneandupdate({ schoolname: req.body.collegename }, { $push: { "schoolcomments": item } }, { new: true }, function(err, college) { if (err) { res.render('errors', { error: 'error' }); } else { res.locals.college = college; res.locals.user = user; res.render('universiteinfouser'); } });
note i've aded { new: true }
in order return modified document college
instead of unaltered one.
fyi, in code, have used js method array.prototype.push()
return new length of array using college.schoolcomments.push
Comments
Post a Comment