10
var mongoose = require('mongoose');
var membersModel = require('./model_member.js');
exports.request_friend_list = function(req, res){
var userid=req.body.userid;
console.log(userid);

//  membersModel.find({_id: userid,friends:{status:0}},{_id:0,'friends':1,},function(err,data)
    membersModel.aggregate(
         {$match: {_id:userid}},
         {$project: {friends: 1}},
         {$unwind: "$friends"},
         {$match: {"friends.status": 0}}
     ,function(err,data){
     if(err){
        res.json({status:"error"});
        throw err;
    }else{
        if(JSON.stringify(data).length > 0){
            console.log(JSON.stringify(data));
            res.json(data);
        }
        else{
            res.json({status: "Data is not Exist."});
            console.log("Data is not Exist.");
        }
    }   
});

membersModel.find({...}) is operating normally, but memberModel.Aggregation({...}) is not working. This also works in MongoDB:

db.members.aggregate({$match:_id: ObjectId("532b4729592f81596d000001"),$project:"friends":1,$unwind:"$friends",$match:"friends.status": 0})

What is the problem?

1 Answer 1

12

The likely problem here is that your userid value is not actually a correct ObjectID type when it is being passed into the pipeline. This results in nothing being "matched" in the initial stage.

Therefore as a more complete example:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectID = require("mongodb").ObjectID;

mongoose.connect("mongodb://localhost/test");

friendSchema = new Schema({
  "name": String,
  "status": Number
});

memberSchema = new Schema({
  friends: [friendSchema]
});

var Member = mongoose.model("Members", memberSchema );

var userid = new ObjectID("537ec520e98bcb378e811d54");

console.log( userid );

Member.aggregate([
  { "$match": { "_id": userid } },
  { "$unwind": "$friends" },
  { "$match": { "friends.status": 0 } }],
  function( err, data ) {

    if ( err )
      throw err;

    console.log( JSON.stringify( data, undefined, 2 ) );

  }
);

Which then will match data as expected:

[
  {
    "_id": "537ec520e98bcb378e811d54",
    "friends": [{
      "name": "Ted",
      "status": 0
    }]
  }
]

So be careful to make sure this is of the correct type. The aggregate method does not automatically wrap a string value such as "537ec520e98bcb378e811d54" into an ObjectID type when it is mentioned in a pipeline stage against _id in the way that Mongoose does this with other find and update methods.

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

1 Comment

Member.aggregate is missing an Array that holds all those objects. It should be Member.aggregate([ {},{},{}....{} ]);

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.