1

Can I get only 1 photo by objectid? I only need to get 1 Image detail from 1 post by photo but what i get is all photo of post.

this is my db structure

enter image description here

and this is my code looks like:

 Post.findOne({
  $and: [
    { photo: { $elemMatch: { _id: id } } }       ]
}).exec((err, post) => {
  if (err) {
    return res.status(400).json({ error: err });
  }
  req.post = post;
  console.log(req.post);
  next();
});

what i get in req.post is only [].

Thanks in advance

3
  • If you want to get a photo by an id, regardless of what post it is, you can do { 'post.photo._id': id } in your search condition Commented Sep 15, 2019 at 9:00
  • I still get all photos. Is it posible to get only 1 from photos by photo objectId ? Commented Sep 15, 2019 at 12:00
  • Im finally getting this one [{ "photo": [{ "_id": "5d7dd20185251921882e2ba1", "data": "", "contentType":"" }] }] Now my problem is I cant get the contentType. undefined on post.photo Commented Sep 18, 2019 at 14:07

2 Answers 2

3

The $elemMatch projection operator provides a way to alter the returned documents, in here coupled with find utilizing second parameter which is projection will achieve that.

Post.find(
  {},
  {
    _id: 0,
    photo: { $elemMatch: { _id: id } }
  }
);

This will provide leaned documents with the promise: .lean().exec():

Post.find(
  {},
  {
    _id: 0,
    photo: { $elemMatch: { _id: id } }
  }
)
  .lean()
  .exec();

NOTE: $elemMatch behaviour is to return the first document where photo's id matches.

Sign up to request clarification or add additional context in comments.

2 Comments

It gives me this [ { photo: [ [Object] ] } ]. I cant get contentType
@kaks That object should contain all properties. You could try with .lean().exec().
1

You can try with aggregate instead of findOne: https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/

Post.aggregate([
    { $match: { 'photo._id': id } },
    { $unwind: "$photo" },
    { $match: { 'photo._id': id } },
]);

Maybe not the best, but single photo data is achievable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.