I need ordering the user's likes with start current user like in prisma - sql

I am using prisma.
I need to get likes of posts with last 3 liked user .
So I want to get these user that starts with current user like .
Becouse I can check is liked this post in frontend part easly.
How can I do this issue with prisma.
Thanks for your help :)
let posts = await prisma.posts.findMany({
where: {
active: true,
},
orderBy: {
id: 'desc'
},
select: {
id: true,
userId: true,
text: true,
files: {
select: {
files: true
}
},
createdAt: true,
active: true,
user: {
select: {
id: true,
fullName: true,
profileImg: {
select: {
url: true
}
}
},
},
_count: {
select: {
likes: true,
comments: true
}
},
likes: {
orderBy: {
id: 'desc'
},
select: {
postId: true,
userId: true,
user: {
select: {
id: true,
fullName: true,
profileImg: {
select: {
url: true
}
}
},
}
},
take: 3
}
},
})

Related

mongodb aggregation query to include a specific field

I have a mongodb schema which looks like
{
post_id: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "Post"
},
comment_by: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "User"
},
comment: {
type: String,
required: true
},
parent_comment_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
},
is_deleted: {
type: Boolean,
default: false
}
}
I want to group the comments such that
they have common "parent_comment_id" but I also want to include the "comment" field of the
document whose "id" is "parent_comment_id".
This is query I have written
var comments = await Comment.aggregate([
{
"$match": {
post_id: mongoose.Types.ObjectId(post_id)
}
},
{
"$group": {
_id: `$parent_comment_id`,
replies: { "$count": {} }
}
}
])
and the result is
{ _id: new ObjectId("6278e11fa7887263e6e6fada"), replies: 3 },
{ _id: new ObjectId("6278fb9f6a8d30c46eb53a84"), replies: 5 },
{ _id: null, replies: 2 }
Result I want
{ _id: new ObjectId("6278e11fa7887263e6e6fada"), replies: 3 , comment : <comment>},
{ _id: new ObjectId("6278fb9f6a8d30c46eb53a84"), replies: 5 , comment : <comment>},
Welcome heeya joshi!.
You can do something like this:
db.collection.aggregate([
{
$match: {post_id: mongoose.Types.ObjectId(post_id)}
},
{
$addFields: {
parent_comment_id: {$ifNull: ["$parent_comment_id", "$_id"]}
}
},
{
$group: {
_id: "$parent_comment_id",
"comment": {
$push: {
$cond: [
{$eq: ["$parent_comment_id", "$_id"]},
"$comment",
"$$REMOVE"
]
}
},
replies: {"$count": {}}
}
},
{
$project: {
comment: {$arrayElemAt: ["$comment", 0]},
replies: 1
}
}
])
As you can see here.
After your $match, the addFields adds the parent_comment_id to the parents themselves. Then the $group keeps the comment only for the parents.

ExpressJs - Mongoose: Delete documents with Many To Many relationship

I've two Models, Post and Tag with Many To Many relationships.
Post Schema:
const postSchema = new Schema(
{
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: [true, 'A post must belong to a user.'],
},
title: {
type: String,
unique: [true, 'A Post already exists with this title.'],
required: [true, 'A Post must have a title.'],
},
slug: { type: String, unique: true },
body: { type: String, required: [true, 'A Post must have a body.'] },
coverImage: String,
images: Array,
isDraft: { type: Boolean, default: false },
isPublished: { type: Boolean, default: false },
tags: [{ type: Schema.Types.ObjectId, ref: 'Tag' }],
},
{
timestamps: { currentTime: () => Math.floor(Date.now() / 1000) },
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
)
Tag Schema:
const tagSchema = new Schema(
{
title: { type: String, required: true },
slug: { type: String },
posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }],
},
{
timestamps: { currentTime: () => Math.floor(Date.now() / 1000) },
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
)
Now I want to remove all the references of the Posts from the Tag documents when a Post is deleted.
I'm trying to the following remove middleware in the Post model but it is not working. The post get deleted but the reference still there on the Tag documents.
postSchema.pre('remove', function (next) {
var post = this
post
.model('Tag')
.update(
{ posts: { $in: post.tags } },
{ $pull: { posts: post._id } },
{ multi: true },
next
)
})
After trying many times I finally fired out what wrong I was doing. Following the fix I made to make it work:
In Post Controller I was previously doing this:
const post = await Post.findByIdAndDelete(req.params.id)
Which I changed to:
const post = await Post.findById(req.params.id)
await post.remove()
And in Post Model:
postSchema.pre('remove', async function (next) {
await this.model('Tag').updateMany(
{ posts: this._id },
{ $pull: { posts: this._id } },
{ multi: true },
next
)
})

Sequelize select with two relations to the same entity

I have 2 tables, ItemLegacy :
module.exports = function(sequelize, DataTypes) {
return sequelize.define('ItemLegacy', {
id: {
type: DataTypes.INTEGER(11).UNSIGNED,
allowNull: false,
primaryKey: true
},
parent: {
type: DataTypes.INTEGER(11),
allowNull: false,
defaultValue: 0,
},
child: {
type: DataTypes.INTEGER(11),
allowNull: false,
defaultValue: 0
}
}, {
tableName: 'ItemLegacy',
timestamps: false,
underscored: false
});
};
and Item :
module.exports = function(sequelize, DataTypes) {
return sequelize.define('Item', {
id: {
type: DataTypes.INTEGER(11).UNSIGNED,
allowNull: false,
primaryKey: true
},
title: {
type: DataTypes.STRING(500),
allowNull: false,
defaultValue: ''
},
code: {
type: DataTypes.STRING(20),
allowNull: true
},
}, {
tableName: 'Item',
timestamps: false,
underscored: false
});
};
I also defined two relationships :
db.ccnLegacy.hasOne(db.ccn, { foreignKey: 'id', sourceKey: 'parent' })
db.ccnLegacy.hasOne(db.ccn, { foreignKey: 'id', sourceKey: 'child' })
My question is, I would like to create a select request using sequelize, with a relation for each of the 2 fields parent and child.
I know how to do that with one relation, but how do I do it with 2 ?
My code with only one relation :
db.itemLegacy.findOne({
raw: true,
where: { child: idChild },
include: [
{
model: db.item
},
]
})
You simply should indicate aliases for both associations and use them in queries. Second is you used hasOne instead of belongTo because belongTo is used exactly in a case when you go from N to 1 in N:1 relationship.
Associations:
db.ccnLegacy.belongsTo(db.ccn, { foreignKey: 'parent', as: 'Parent' })
db.ccnLegacy.belongsTo(db.ccn, { foreignKey: 'child', as: 'Child' })
Query:
db.itemLegacy.findOne({
raw: true,
where: { child: idChild },
include: [
{
model: db.item,
as: 'Child'
},
{
model: db.item,
as: 'Parent'
},
]
})

Apollo-Client | No result from query when using certain fields

I'm trying to use apollo-client in my react-native app but for some reason I can only get results from queries when I use certain fields.
Here's my first query :
`query RootQueryType($page: Int!) {
events(page: $page) {
title
}
}`
Working perfectly in RN and GraphiQL but as soon as I add or use an other field than title I don't get any result from the query in RN. It's working perfectly in GraphiQL and there's no error at all.
For example :
`query RootQueryType($page: Int!) {
events(page: $page) {
description
}
}`
Here's my event type :
const EventType = new GraphQLObjectType({
name: 'EventType',
fields: () => ({
id: { type: GraphQLID },
title: { type: GraphQLString },
category: { type: GraphQLString },
description: { type: GraphQLString },
terminated: { type: GraphQLBoolean },
coverUrl: { type: GraphQLString },
startDate: { type: GraphQLString },
endDate: { type: GraphQLString },
price: { type: GraphQLFloat },
website: { type: GraphQLString },
ticketsUrl: { type: GraphQLString },
geometry: { type: GraphQLString },
participantsCount: { type: GraphQLInt },
participants: {
type: new GraphQLList(UserType),
resolve(parentValue) {
return Event.findParticipants(parentValue.id);
}
}
})
});

Bind KendoUI grid with Model data in MVC 4

For example, I have a view with model IEnumerable<Correspondence>. I want to bind it to KendoUI grid. What should I do? I've tried
#model IEnumerable<Correspondence>
<div id="Correspondence"></div>
<script>
$(document).ready(function () {
$('#Correspondence').kendoGrid({
dataSource: {
data: #Html.Raw(Json.Encode(Model)),
editable: { destroy: true },
batch: true,
pageSize: 15,
schema: {
model: {
id: "Id",
fields: {
Subject: { type: "string" },
CorrespondenceType: { type: "number" },
SentDate: { type: "date" }
}
}
}
},
navigatable: true,
selectable: "row",
filterable: true,
sortable: true,
pageable: {
refresh: true,
pageSizes: true
},
columns: [
{
title: "Subject",
field: "Subject"
},
{
title: "Type",
field: "CorrespondenceType"
},
{
title: "Sent Date",
field: "SentDate",
format: "{0:MM/dd/yyyy}"
},
{
command: [{ name: "openCorrespondence", text: "Open", className: "k-grid-openLaboratory", imageClass: "k-icon k-i-maximize", click: Open },
{ name: "deleteCorrespondence", text: "Delete", className: "k-grid-deleteLaboratory", imageClass: "k-icon k-delete", click: Delete },
{ name: "EditCorrespondence", text: "Edit", className: "k-grid-editLaboratory", imageClass: "k-icon k-edit", click: Edit }],
title: "Action"
}
]
});
}); // end ready
</script>
But it doesn't work. The table even doesn't show up. Please help me. Thank you.
Edited!!!
I have solved my own problem. Because I used command column, so I have to add 3 functions: Open, Edit, and Delete. Then, the grid showed successfully.