user2129896
user2129896

Reputation: 307

Node.js - Angular - MongoDB - for `userid` , get `username`

I have such mongoose.Schema:

User.js:

const mongoose = require('mongoose');
const bcrypt = require('bcrypt-nodejs');
const Schema = mongoose.Schema;

const UserSchema = new Schema({

    username: String,
    password:  String,      
    email:  String,      
});

module.exports = mongoose.model('users', UserSchema, 'users');

product.js:

const mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
const Schema = mongoose.Schema;

const ProductSchema = new Schema({

    userid: {type:String, required: true},
    product_name: {type:String, required: true}     
});

ProductSchema.plugin(mongoosePaginate);
module.exports = mongoose.model('products', ProductSchema, 'products');

method:

exports.selectUsersProductsCount = function (req, res, next) {

  Product.aggregate([
    {"$group" : {_id:{userid:"$userid" }, count:{$sum:1} }   }
],
function(err, result) {
    if(err){ res.status(400).json({ success: false, message:'Error processing request '+ err }); }
        res.status(201).json({
          success: true,
          data: result
    });
    console.log(result);
})

}

result:

[ { _id: { userid: '5ab655bbb94733156c438112' }, count: 3 },
  { _id: { userid: '5ab425c6f5bff145304092f7' }, count: 1 } ]

I want the username field to be displayed as well. I do not know how to use join. Counts correctly, but does not display the username field.

How to correct the aggregate method to display: userid, username, count

[ { _id: { userid: '5ab655bbb94733156c438112', username: 'Jon Alon' }, count: 3 },
  { _id: { userid: '5ab425c6f5bff145304092f7', username: 'Jonson Con' }, count: 1 } ]

examples data:

Product

{
    _id:O bjectId(5ab7da972ade533790268f47),
    userid:"5ab655bbb94733156c438112",
    product_name:"gs",
    __v:0
},{
    _id: ObjectId(5ab7daa92ade533790268f48),
    userid:"5ab655bbb94733156c438112",
    product_name:"dg",
    __v:0 
}

User

{
    _id: ObjectId(5ab655bbb94733156c438112),
    username: "rrrr",
    email:"rrrr",
    __v:0 
}

enter image description here

Upvotes: 1

Views: 573

Answers (2)

user2129896
user2129896

Reputation: 307

solution

products.aggregate([

  {$lookup:{
    from: "users",
    localField: "ObjectId(userid)",
    foreignField: "ObjectId(_id)",
    as: "users"
  }},


{ "$group" :
  {
    _id: { userid: "$userid" },
    name: { $last: "$users.username" } ,
    count: { $sum: 1 }
  }
}, {$sort: {"_id.userid":  1}}

  ], function(err, result) {
      console.log(result);
      if(err){ res.status(400).json({ success: false, message:'Error processing request '+ err }); }
          res.status(201).json({
            success: true,
            data: result
      });  
    }
  );
}

returns:

[ { _id: { userid: '5ab425c6f5bff145304092f7' },
    name: [ 'cccc', 'rrrr', 'zzzz' ],
    count: 3 },
  { _id: { userid: '5ab655bbb94733156c438112' },
    name: [ 'cccc', 'rrrr', 'zzzz' ],
    count: 1 },
  { _id: { userid: '5aba7e8c045115340496becd' },
    name: [ 'cccc', 'rrrr', 'zzzz' ],
    count: 2 } ]

Upvotes: 0

Graciano
Graciano

Reputation: 518

You have to use the $lookup function to achieve that but you need to have some property in common between the 2 collections. You would need to add userId on UserSchema or some other property so you could "join"

In your example u could try

db.product.aggregate([ {$lookup:{ from: "user", localField: "ObjectId(userid)", foreignField: "ObjectId(_id)", as: "username" }}, {"$group" : {_id:{userid:"$userid", username : "$username" }, count:{$sum:1} } } ])

enter image description here

Upvotes: 1

Related Questions