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
- feed.url
- comment.url
- 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"}})
but updates when comments.url
or comments.username
matches 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
Post a Comment