populate or aggregator, how? - mongodb

I want to get only all messages related to the projects posted by user.
I don't think there is a way to do so using populate because we have to get the user id from the other collection and then render messages using his id which is "submittedBy" in the project schema.
I am trying aggregator but it is also not working.
Any help or clue would be appreciated.
message Schema:
const MessageSchema = new Schema({
content:{
type: String,
trim: true
},
projectId:{
type: Schema.Types.ObjectId,
ref: 'Form'
},
imageId:{
type: Schema.Types.ObjectId,
ref: 'Image'
},
sender:{
type: Schema.Types.ObjectId,
ref: 'User'
},
readBy:[{
type: Schema.Types.ObjectId,
ref: 'User'
}],
}, {timestamps:true});
Project schema:
const FormSchema = new Schema({
submittedBy: {
type: Schema.Types.ObjectId,
ref: 'User'
},
logoName: {
type: String,
trim: true
},
industry: [{
type: String,
trim: true
}],
logoType: [{
type: String,
trim: true
}],
colors: [{
type: String,
trim: true
}],
tagline: {
type: String,
trim: true
},
org: {
type: String,
trim: true
},
communicate: {
type: String,
trim: true
},
deadline : {
type: String,
trim: true
},
services: {
type: String,
trim: true
},
package: {
type: String,
trim: true
},
assignedTo: {
type: String,
trim: true
}
}, {timestamps:true})
I tried population but I don't think it will work or efficient.
So I am using aggregation but it's not working:
var objId = mongoose.Types.ObjectId(req.session.user._id);
results = await Model.aggregate([
{
$lookup:
{
from: "forms",
localField: "projectId",
foreignField: "_id",
as: "tags"
}
},
{ $unwind: "$tags" },
{$match:{ 'tags.submittedBy': userId }},
]).exec(function(err, results) {
console.log(results)
});
Result After Combining two collections:
{
_id: 609bd3772583c56dd3e302d3,
readBy: [],
content: 'Remove Tagline and align.',
sender: 604db5708cf232652cd4469e,
imageId: 6099964c2583c56dd3e302c3,
projectId: 60968eed2583c56dd3e302ac,
createdAt: 2021-05-12T13:09:11.060Z,
updatedAt: 2021-05-12T13:09:11.060Z,
__v: 0,
tags: {
_id: 60968eed2583c56dd3e302ac,
industry: [Array],
logoType: [Array],
colors: [Array],
logoName: 'global consultancy services',
tagline: 'Follow your dreams',
org: 'We guide students who seeks to study overseas e.g. the UK. We offer consultancy services to students from selecting a university to getting visa and then getting in the country.',
communicate: '3 concepts\r\n' +
'Keep "Indra global " big AND bold\r\n' +
'and "consultancy services" below it.\r\n' +
'In one concept you can use IGCS initials to create icon form'
deadline: '2021-05-12',
services: '',
package: 'undefined',
submittedBy: 60968eed2583c56dd3e302ab,
createdAt: 2021-05-08T13:15:25.661Z,
updatedAt: 2021-05-10T08:28:18.587Z,
__v: 0,
assignedTo: '6050d8485cc8bb6a20ef36fa'
}
}
]

Related

Mongoose - Sub Document Array Issue

I have a "Company" Model which has a number of "Rooms".
I'm able to create the Rooms no problem, and they have a link back to the Company.
The problem is that when I get the Company, the Rooms array has no items.
I can see that the Room exists and has a link back to the Company:
{
"RoomType": 0,
"AllowedRoomRoles": [
"5f999f4f542eed1b8fce5fa9"
],
"Enabled": true,
"_id": "5fb677b453658c7070bf9433",
"RoomName": "Martins Room 2",
"RoomPin": "0001",
"Company": "5fad553db19ca100161a0d8f",
"__v": 0
}
However when I do:
var company = await CompanyModel.findById('5fad553db19ca100161a0d8f');
I get the Company back but the Rooms array has no items in it.
Here are my models:
//Room Schema:
const roomSchema = new Schema({
RoomPin: String,
RoomName: String,
RoomType: { type: RoomType, default: RoomType.MeetingRoom } ,
Company: {type: Schema.Types.ObjectId, ref: 'CompanySchema'},
AllowedRoomRoles: [{type: Schema.Types.ObjectId, ref: 'RoomRoleSchema'}],
Enabled: { type: Boolean, default: true },
}, {
collection: "room"
})
//Company Schema:
const companySchema = new Schema({
CompanyName: { type: String, required: true },
CompanyLogo: { type: String, required: true },
Enabled: { type: Boolean, default: true },
CompanyIdentifier: { type: String, required: true },
CompanyWebsite: { type: String, required: true },
Rooms: [{type: Schema.Types.ObjectId, ref: 'RoomSchema'}],
}, {
collection: "company"
})
Minor update:
Seems doing it this way around is fine?
```var rooms = await RoomModel.find({'Company': company._id.toString() });

Is it possible to have two types of objects in an array of mongoose schema

I am building an e-commerce application and this is my orders schema.
const mongoose = require("mongoose");
const orderSchema = new mongoose.Schema({
buyer: {
type: mongoose.Schema.Types.ObjectId,
ref: "buyer",
required: true
},
items: [{
item: {
type: mongoose.Schema.Types.ObjectId,
ref: "item",
},
quantity: {
type: Number,
default: 1
}}
],
seller: {
type: mongoose.Schema.Types.ObjectId,
ref: "seller",
required: true
},
location: {
type: {
type: "String",
enum:['Point']
},
coordinates: {
type: [Number],
index: '2dsphere'
}
},
sendAt:{
type: Date,
default: Date.now
}
});
const orderModel = mongoose.model("orders", orderSchema);
module.exports = orderModel;
I want to have an array having item-reference-id and quantity.
But with the above schema when i enter data, each item is acting as an another sub-document and having _id. Query response image.
I have found solution:
order: [
{
_id: false,
item: {
type: mongoose.Schema.Types.ObjectId,
ref: "items",
required: true,
},
quantity: { type: Number },
},
],
_id: false will stop the subdocument from creating another id for the subdocument.

Associate one schema with another

I have my user schema:
const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
date: { type: Date, default: Date.now },
active: { type: Boolean, default: false }
});
I want to create a leave status schema. Data will be given by only one user about all leave status. I want to associate each one of the leave status to there respective user schema id. I tried leave status schema as the following:
const leaveSchema = new Schema({
leave: [
{
email: { type: String, required: true },
month: { type: String, required: true },
year: { type: Number, required: true },
earnedleave: { type: Number },
sickleave: { type: Number },
festivalleave: { type: Number },
compoff: { type: Number }
}
]
});
How can i associate my emailid with userschema. Can it be possible? If so, how can i tweak it?
We don't need to associate the schema to get leave based on user, You can use aggregation for that,
db.user.aggregate([
...
{$lookup: {from: "leave", localField: "email", foreignField: "leave.email", as: "leaves"}},
...
]);
Still, If you like to associate two collection, You have to use ref using ObjectId
const leaveSchema = new Schema({
leave: [
{
user: { type: Schema.Types.ObjectId, ref: 'user' }, //Your model name as reference
email: { type: String, required: true },
month: { type: String, required: true },
year: { type: Number, required: true },
earnedleave: { type: Number },
sickleave: { type: Number },
festivalleave: { type: Number },
compoff: { type: Number }
}
]
});

Need help to make mongo $lookup query

This is my table structure
Group -> _id,name,description,type
GroupMembers -> _id, group(FK),status,Isinvited, user_id(Fk)
User -> _id,name,email,role
Need :- I want to get groups with its active members (status = true) aslo need the name of users from User collections
Current Code :-
Group.aggregate([
{
$lookup: {
from: "groupmembers",
localField: "_id",
foreignField: "group",
as: "membersList"
}
},
{
$lookup : {
from: "users",
localField: "membersList.user",
foreignField: "_id",
as: "userss"
}
},
{
$match:{"_id" : mongoose.Types.ObjectId("5abe70eb7ede1b695e9342d6")}
},
{
$project:{"_id":1,"name":"$name","member":{"membersList":"$membersList","userss":"$userss"}}
}
])
Getting the response but not in well manners go like ->
[
{
"_id": "5abe70eb7ede1b695e9342d6",
"name": "Welcome To Hobnobbin",
"member": {
"membersList":["Got memebrsLiset from GroupMembers"],
"userss": ["Got users from groupMembers FK "]
}
}
]
How can I get it like
[
{
"_id": "5abe70eb7ede1b695e9342d6",
"name": "Welcome To Hobnobbin",
"member": {
"membersList":["Got memebrsLiset from GroupMembers",user: "Userobject here"],
}
}
]
Collections : ->
var GroupSchema = new Schema({
name: {
type: String,
required: 'Please fill Group name',
trim: true
},
photo:{
type:String
},
type: {
type: [{
type: String,
enum: ['child', 'adult']
}],
required: 'Please select at least one type'
},
description:{
type:String,
default:''
},
pinnedTweet:{
type:String,
default:''
},
/*members: [{
type: Schema.ObjectId,
ref: 'User'
}],*/
jointype: {
type: String,
enum: ['openToJoin', 'openToRequest', 'inviteOnly'],
default: 'openToJoin',
required: 'Please select at least one behavious of group'
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
createByHobnob: {
type: Boolean,
default: false
},
isWelcomeGroup: {
type: Boolean,
default: false
},
allowPrivateChat: {
type: Boolean,
default: false
}
});
var GroupMemberSchema = new Schema({
user : {
type: Schema.ObjectId,
ref: 'User'
},
group : {
type: Schema.ObjectId,
ref: 'Group'
},
role: {
type: String,
enum: ['member', 'ban', 'moderator', 'admin'],
default: 'member',
required: 'Please select at least one role'
},
is_active: {
type: Boolean,
default: false
},
is_invited: {
type: Boolean,
default: false
},
created: {
type: Date,
default: Date.now
},
allowChat: {
type: Boolean,
default: true
}
});
var UserSchema = new Schema({
firstName: {
type: String,
trim: true,
default: ''
},
lastName: {
type: String,
trim: true,
default: ''
},
displayName: {
type: String,
trim: true
},
email: {
type: String,
unique: true,
lowercase: true,
trim: true,
default: '',
validate: [validateLocalStrategyEmail, 'Please fill a valid email address']
}
});

MongoDB: How to find the relationships between collections in database

I have a collection of user which has id, firstName, lastName. id field of user collection has been used in another collection.
Is there any way to find all collection which used user id?
user schema:
let userSchema = new mongoose.Schema({
firstName: {
type: String,
trim: true,
required: true
},
lastName: {
type: String,
trim: true,
required: true
}
},
{
timestamps: true,
usePushEach: true
});
training schema:
var trainingSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
name: {type: String, required: true},
institution: {
instituteName: {type: String, required: true},
type: {type: String, required: true},
address: {
country: String,
state: String,
city: String
}
},
startDate: Date,
endDate: Date,
achievements: String,
createdAt: Date,
updatedAt: Date,
endorsers: [{
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
profilePic: {
container: {type: String,default: null},
name: { type: String, default: null }
},
currentPosition: {type: String,default: ""},
currentWorkingCompany: {type: String,default: ""}
}],
});
In above schema userId come from user collection
Note: similar to this which is available in MYSQL:
SELECT
ke.referenced_table_name 'parent table',
ke.referenced_column_name 'parent column',
ke.table_name 'child table',
ke.column_name 'child column',
ke.constraint_name
FROM
information_schema.KEY_COLUMN_USAGE ke
WHERE
ke.referenced_table_name IS NOT NULL
AND table_schema = 'your_db_name'
ORDER BY ke.referenced_table_name;
Source: here
You probably need MySQL function named join. In MongoDB it is named $lookup and it is part of aggregate function.