node.js - How to find a sub document in mongoose without using _id fields but using multiple properties -


i have sample schema -

comment.add({     text:string,     url:{type:string,unique:true},     username:string,     timestamp:{type:date,default:date} }); feed.add({     url:{type:string, unique:true },     username:string,     message:{type:string,required:'{path} required!'},     comments:[comment],     timestamp:{type:date,default:date} }); 

now, don't want expose _id fields outside world that's why not sending clients anywhere. now, have 2 important properties in comment schema (username,url) want update content of sub document satisfies

  1. feed.url
  2. comment.url
  3. comment.username

if comment.username same client value req.user.username update comment.text property of record url supplied client in req.body.url variable.

one long , time consuming approach thought first find feed given url , iterating on subdocuments find document satisfies comment.url==req.body.url , check if comment.username==req.user.username if so, update comment object. but, think there must easier way of doing this? tried -

db.feeds.update({"username":"harshitladdha93@gmail.com","comments.username":"harshitladdha3@gmail.com","comments.url":"test"},{$set:{"comments.$.text":"updated text 2"}}) 

found http://www.tagwith.com/question_305575_how-to-find-and-update-subdocument-within-array-based-on-parent-property

but updates when comments.url or comments.usernamematches other sub documents

and tried

db.feeds.distinct("comments._id",{"comments.url":req.body.url}) 

to find _id of document associated url returns _id in subdocument

first off - should not rely on _id not being seen outside world in terms of security. bad idea multitude of reasons (primarily rest , fact it's returned default queries).

now, address question, want $elemmatch operator. says you're looking specified sub-document within array matches multiple queries.

e.g.

db.feeds.update({     "username":"harshitladdha93@gmail.com",     comments: {         $elemmatch: {             username: "harshitladdha3@gmail.com",             url: "test"         }     } }, {$set: {"comments.$.text":"updated text 2"}}) 

if don't use $elemmatch you're saying you're ok document if of comments match query - i.e. if there comment user "harshitladdha3@gmail.com", , separate comment has url "test", document match unless use $elemmatch


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -