Reputation: 492
I want to display list files of particular user (_id: 876896) with their click counts as below:
Sr. No. | File Name | Click Count
Below is the sample schema I am using:
var clicks = mongoose.Schema({
file_id : String,
IP : String
});
var files = mongoose.Schema({
filename : String,
owner : {type:mongoose.Schema.ObjectId, ref:'users'},
});
How effectively this can done.
Upvotes: 3
Views: 1013
Reputation: 23515
You can do it in two step, first get all files that refer to the users you want data for. Then, get alls clicks that are related to files you read. There is no INNER_JOIN in mongodb
Little example:
files.find({
owner: {
$in: usersIdsArray // [_id, _id...] ids of all users
},
}).then((ret = []) => {
// Here ret is array of files
if (!ret.length) // There is no files matching the user
return clicks.find({
file_id: {
$in: Array.from(ret, x => x._id.toString()),
// build an array like [_id, _id, _id...]
},
});
}).then((ret = []) => {
// Here you have all clicks items
});
I also recommend to use embedded schema instead of multiple collections:
var clicks = mongoose.Schema({
file_id: String,
IP: String
});
var files = mongoose.Schema({
filename: String,
owner: {type:mongoose.Schema.ObjectId, ref:'users'},
});
turn into:
var files = mongoose.Schema({
filename: String,
owner: {type:mongoose.Schema.ObjectId, ref:'users'},
clicks: [String], // With String your IP
});
MongoDB is good when it comes to big data, but not that good in relations.
Upvotes: 3