mongoose find if array of references of a document contains an IdObject - mongodb

im using nodejs express and mongodb
this is part of my schema:
var UserSchema = mongoose.Schema({
friends: [{
type: mongoose.Schema.Types.ObjectId,
ref: "User",
unique: true
}],
sentRequests: [{
type: mongoose.Schema.Types.ObjectId,
ref: "User",
unique: true
}],
receivedRequests: [{
type: mongoose.Schema.Types.ObjectId,
ref: "User",
unique: true
}]
}
var User = mongoose.model('User', UserSchema);
i want to query if a user with a specefic id is in any array ** (friends, sentRequests or receivedRequests) **of another user :
i used this approach but I have to do this for 3 arrays and it's slow:
UserSchema.statics.relStatus = function(User1ID, User2ID) {
var User = this;
User.find({
_id: User1ID,
friends: {
_id: User2ID
}
}).then((err, res) => {
if (res) {
return ' they are friends';
}
});

You can try with following aggregation query (if you are using mongo 3.4 or higher):
User.aggregate([
{ $match: { _id: User1ID } },
{
$facet: {
friends: [{ $match: { friends: User2ID } }],
sentRequests: [{ $match: { sentRequests: User2ID } }],
receivedRequests: [{ $match: { receivedRequests: User2ID } }]
}
},
{
$project: {
relationship: {
$switch: {
branches: [
{ case: { $anyElementTrue: [ "$friends" ] }, then: "friends" },
{ case: { $anyElementTrue: [ "$sentRequests" ] }, then: "sentRequests" },
{ case: { $anyElementTrue: [ "$receivedRequests" ] }, then: "receivedRequests" },
],
default: false
}
}
}
}
])
Result will be object in following format {relationship: "<RELATIONSHIP_TYPE>"}
or {relationship: false} if they have no relationship.
First stage of the aggregation pipeline will match single document by _id (which is indexed by default), so you shouldnt have any performance issues.

In order to query for multiple field you can user '$or'.
User.find({
_id: User1ID,
{
$or: [
{friends: $in:[User2ID]},
{sentRequests: $in:[User2ID]},
{receivedRequests: $in:[User2ID]}
]
}
}).then((err, res) => {
if (res) {
return ' they are friends';
}
});
$or will return a user which have User2ID in either 'friends' or 'sentRequests' or 'receivedRequests'.
Read more about '$or' and '$in'
Hope this helps.

Related

Grouping documents in mongoose

I am building a chat app using nodejs and mongoose. I need to retrieve chats for a user(logged in user) such that the retrieved data/chats will contain the latest message and the name of the user the logged in user had a chat with. I am not able to come app with a way to aggregate the data since the sender can also be a recipient in a chat. My message schema is shown below.
const messageSchema = new mongoose.Schema(
{
content: { type: String, required: true },
fromUser: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
toUser: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
users: Array,
messageRead: { type: Boolean, default: false },
},
{
timestamps: true,
}
);
The purpose of this is to have a list of chats render on the front end which when clicked will open an inbox containing messages between the two users.
You can just use the $or operator. This way it will return all elements where the user is the sender or recipient:
.aggregate([
{
$match: {
$or: [
{
fromUser: ObjectId("<UserID>")
},
{
toUser: ObjectId("<UserID>")
}
]
}
},
{ $sort: { createdDate: -1 } },
{ $limit: 1 },
])
Edit after feedback via chat
I grouped the documents by using the users array and basically just output all fields as in the initial document:
.aggregate([
{
$match: {
users: ObjectId("<UserID>")
}
},
{
$group: {
_id: "$users",
out: {
$top: {
output: {
_id: "$_id",
content: "$content",
fromUser: "$fromUser",
toUser: "$toUser",
users: "$users",
messageRead: "$messageRead",
createdAt: "$createdAt"
},
sortBy: {
createdAt: -1
}
}
}
}
},
{
"$replaceRoot": {
"newRoot": "$out"
}
}
])

Aggregate $lookup Array of Objects

I have collection schools with field groups and I am attempting to $lookup documents from the users collection. I am getting empty results however and an extra schools document.
Schools Schema
const SchoolSchema = new Schema({
groups: [
{
name: { type: String },
color: { type: String },
userDrivenName: { type: String },
},
]
});
module.exports = School = mongoose.model("School", SchoolSchema);
User Schema
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
groups: [
{
groupId: { type: String },
name: { type: String },
color: { type: String },
userDrivenName: { type: String },
},
]
});
Query
db.schools.aggregate([
{
$match: {
_id: ObjectId("5d836e584a24e20e6090fd7b")
}
},
{
$project: {
groups: 1
}
},
{
$unwind: "$groups"
},
{
$lookup: {
from: "users",
let: {
groupId: "$groups._id"
},
pipeline: [
{
$match: {
"groups.groupId": "$$groupId"
}
}
],
as: "groups",
},
},
])
Results:
[
{
"_id": "5d836e584a24e20e6090fd7b",
"groups": []
},
{
"_id": "5d836e584a24e20e6090fd7b",
"groups": []
}
]
Expected Results:
[
{
"_id":"5d836e584a24e20e6090fd7b",
"groups":[
{
"_id":"5ec01fdc1dfb0a4f08316dfe",
"name":"GROUP 1",
"users":[
{
"name":"Luke Skywalker"
}
]
}
]
}
]
MongoPlayground
Two things:
There's a type mismatch between groupId and groups.groupId so you need to use $toString (based on your Mongo Playground example),
$lookup with custom pipelines allows only expression when you use $match so you need $in and $expr:
{
$lookup: {
from: "users",
let: { groupId: { $toString: "$groups._id" } },
pipeline: [
{
$match: {
$expr: {
$in: ["$$groupId","$groups.groupId"]
}
}
}
],
as: "groups"
}
}
Mongo Playground

Query embedded document in mongoDB

I'm trying to query a Group document that has Users sub documents.
But I only want the subdocuments that belong to the user,
but I'm also getting data of other users.
Look at the query result, UserStatus field, only one of them belongs to the user.
The query result -
[
{
"_id": "5b1bcc12d5cdbf2cf78f2133",
"name": "First group ever",
"users": [
{
userId: 1,
"userStatus": "I"
},
{
userId: 2,
"userStatus": "I"
}
]
}
]
Group.js -
const GroupSchema = mongoose.Schema({
name: {
type: String,
required: true
},
users: [{
userId: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'users',
required: true
},
userStatus: {
type: String,
required: true
}
}]
})
Query -
Group.find({
"users": {
$elemMatch: {
userId: req.params.id,
$or: [{
userStatus: "I"
}, {
userStatus: "A"
}]
}
}
}, "_id name users.userStatus",
function (err, groups) {
if (err)
res.send(err)
res.json(groups);
});

Check follow status in aggregate mongo / mongoose

I have this schema for users where followers/followed is array and the reference the same schema
var userSchema = new Schema({
username: { type: String, unique: true, trim: true, required: true },
password: { type: String, required: true },
followers: [{ type: Schema.Types.ObjectId, ref: "users" }],
followed: [{ type: Schema.Types.ObjectId, ref: "users" }],
registered: { type: Date, default: Date.now },
admin: { type: Number, default: 0 }
});
What I am looking for to return the follow status, if the _id is contains in followed array give me for example follow_status: 1
[
{
$match: { username: new RegExp(username, "i") }
},
{
$unwind: "$followers"
},
{
$lookup: {
from: "users",
localField: "followers",
foreignField: "_id",
as: "info"
}
},
{
$unwind: "$info"
},
{
$project: {
info: {
_id: 1,
username: 1,
avatar: { $ifNull: ["$avatar", ""] },
fullname: { $ifNull: ["$fullname", ""] }
}
}
},
{
$replaceRoot: { newRoot: "$info" }
},
{
$limit: 1000
}
]
Current pipeliens result
[
{
"_id": "5a906653f52e66c9c7a23cb6",
"username": "User1"
},
{
"_id": "5a908eb564a726cf8ec7e0a3",
"username": "User2"
}
]

Check if value don't exists in sub document of sub document

I the following schema.
var UserSchema = new Schema({
messages: [{
username: String,
read: [{
type: { type: String, enum: ['A','B','C'] },
}]
}],
});
var MySchema = new Schema({
users: [UserSchema]
});
I need to count how many occurrences in MySchema that the last message of each user don't have the read value as 'A'
I need to use aggregate, so that I can join with an existing query.
This should work, if it does not please include some sample data and expected result so that I will update my answer later:
db.collection.aggregate([
{
$unwind: '$users',
},
{
$project: {
lastMessage: {
$arrayElemAt: ['$users.messages', -1],
},
},
},
{
$unwind: '$lastMessage.read',
},
{
$group: {
_id: '$_id',
read: {
$push: '$lastMessage.read',
},
},
},
{
$match: {
read: {
$nin: ['A']
}
}
},
{
$count: 'count'
}
])