0

while i was going through my problem on StackOverflow,i noticed same question was asked before aswell,but none of them had got a good response,or an actual answer.

Mongoose Find One on Nested Object

How can I find nested objects in a document?

well back to my question: i wanted to find the object that is nested in the schema. trying findMany gives all the objects,and findOne give just the first one,but i want particular objects whose id i pass through req.body.checkbox. my JS code goes like..

    app.post("/data", uploads, function (req, res) {
User.findById(req.user.id, function (err, foundUser) {
    if (err) {
      console.log(err);
    } else {
      if (foundUser) {

        var checkedBox = req.body.checkbox;
console.log(checkedBox);
User.findMany({_id:foundUser._id},{comments:{$elemMatch:{_id:checkedBox}}} ,function(err,checkedobj){

  if(err){
    console.log(err);
  }
  else{
  console.log(checkedobj.comments);




    if (Array.isArray(checkedobj.comments)) {
      res.render("checkout",{SIMG: checkedobj.comments});
    } else {
      res.render("checkout",{SIMG: [checkedobj.comments]});
    }

  }
})

      }
    }
  });
});

here is my schema,for reference

 const commentSchema = new mongoose.Schema({
  comment: String,
  imagename: String,
    permission:{type:Number,default:0},
});

const Comment = new mongoose.model("Comment", commentSchema);

const userSchema = new mongoose.Schema({
  firstname: String,
  lastname: String,
  email: String,
  password: String,
  comments: [commentSchema],
  permission:{type:Number,default:0},
});

userSchema.plugin(passportLocalMongoose);

const User = new mongoose.model("User", userSchema);

example

{ 
    "_id" : ObjectId("5ec3f54adfaa1560c0f97cbf"), 
    "firstname" : "q", 
    "lastname" : "q", 
    "username" : "q@q.com", 
    "salt" : "***", 
    "hash" : "***", 
    "__v" : NumberInt(2), 
    "comments" : [
        {
            "permission" : NumberInt(0), 
            "_id" : ObjectId("5ec511e54db483837885793f"), 
            "comment" : "hi", 
            "imagename" : "image-1589973477170.PNG"
        }
    ], 
    "permission" : NumberInt(1)
}

also when i check 3 checkboxes, console.log(checkBox) logs:

[
  '5ec543d351e2db83481e878e',
  '5ec589369d3e9b606446b776',
  '5ec6463c4df40f79e8f1783b'
]

but console.log(checkedobj.comments) gives only one object.

[
  {
    permission: 0,
    _id: 5ec543d351e2db83481e878e,
    comment: 'q',
    imagename: 'image-1589986259358.jpeg'
  }
]
Riyazat Durrani
  • 588
  • 1
  • 8
  • 20

2 Answers2

1

You can make use of findById() method, more documentation about it is provided here

You can use something like this to search by object id:-

var id = "123";
userSchema.findById(id, function (err, user) { ... } );

Hope this helps!

zenwraight
  • 2,002
  • 1
  • 10
  • 14
1

When you want multiple matching elements from an array you should use $filter aggregation operator

And as a precaution, first check req.body.checkbox is an array or not and convert it into an array of ObjectIds

app.post("/data", uploads, function (req, res) {
var ObjectId = mongoose.Types.ObjectId;
User.findById(req.user.id, function (err, foundUser) {
    if (err) {
      console.log(err);
    } else {
      if (foundUser) {

var checkedBox = req.body.checkbox;
if (!Array.isArray(checkedBox)) {
    checkedBox = [checkedBox]
}
console.log(checkedBox);
var checkedBoxArray = checkedBox.map(id => ObjectId(id))
User.aggregate([
   {$match: {_id: foundUser._id}},
   {
      $project: {
         comments: {
            $filter: {
               input: "$comments",
               as: "comment",
               cond: { $in: [ "$$comment._id", checkedBoxArray ] }
            }
         }
      }
   }
],function(err,checkedobj){

  if(err){
    console.log(err);
  }
  else{
  console.log(checkedobj[0].comments);




    if (Array.isArray(checkedobj[0].comments)) {
      res.render("checkout",{SIMG: checkedobj[0].comments});
    } else {
      res.render("checkout",{SIMG: [checkedobj[0].comments]});
    }

  }
})

      }
    }
  });
});

Working example - https://mongoplayground.net/p/HnfrB6e4E3C

Above example will return only 2 comments matching the ids

Puneet Singh
  • 3,477
  • 1
  • 26
  • 39