Trending Posts Mongoose efficient way to do it? - database

How to do trending posts by views from a given day, month, etc and then make a data visualization in each post.
I thought about adding timestamps to each view but I don't know if it will be efficient and if it is the way to do something like this(If I would go with this solution, how much more space it would take in DB?).
Every time a user hits post URL, I add +1 to views and set a cookie to not add views on refresh by the same user. and then I save final to MongoDB.
for example how to achieve something like on NPM site with downloads data visualization
My Schema
const postsSchema = new mongoose.Schema({
title: String,
category: String,
shortDesc: String,
className: String,
description: String,
date: { type: Date, default: Date.now },
hidden: { type: Boolean, default: true },
nsfw: { type: Boolean, default: false },
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'App',
},
],
user: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
username: String,
country: String,
},
meta: {
downloads: {
type: Number,
default: 0,
},
fav: {
type: Number,
default: 0,
},
views: {
type: Number,
default: 0,
},
},
versions: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Version',
},
],
lastUpdate: Date,
});

Related

How can I insert mongo changes in the deploy website?

My website is running allright and it's connected with Database.
I had to add more informations in my Mongo's collection. (I created the ActionPlanSchema).
import mongoose from "mongoose";
import mongoose_delete from "mongoose-delete";
const VerificationSchema = new mongoose.Schema({
text: { type: String, required: true },
});
const ActionPlanSchema = new mongoose.Schema({
title: { type: String, required: true },
mouraTitle: { type: String, required: true },
text: { type: String, required: true },
});
const RequirementSchema = new mongoose.Schema({
itemNumber: { type: String, required: true },
normPart: {
type: mongoose.Schema.Types.ObjectId,
ref: "NormPart",
required: true,
},
generalRequirement: {
type: mongoose.Schema.Types.ObjectId,
ref: "GeneralRequirement",
required: true,
},
specificRequirementDescription: { type: String, required: true },
subject: { type: mongoose.Schema.Types.ObjectId, ref: "Subject" },
criterion: String,
verification: [VerificationSchema],
actionPlan: [ActionPlanSchema],
});
RequirementSchema.index({ itemNumber: 1, normPart: 1 });
RequirementSchema.index({ specificRequirementDescription: 1 });
RequirementSchema.plugin(mongoose_delete, {
overrideMethods: "all",
deletedAt: true,
deletedBy: true,
indexFields: ["deleted"],
});
export default RequirementSchema;
And using a router in Postman (PUT method), I added some information to the Database ActionPlanSchema. Looking like that:
In my localhost, the actionPlan information it's showing. But when I do the deploy, the actionPlan gets undefined.
I believe that it's because the informations that I added in Postman weren't sent to the database used on the Deploy App.
How can I solve this problem? (I don't know if I could be very clear about my issue)
Anyway, thanks so much!

Why is my mongoose populate query throwing "Cannot populate path because it is not in your schema" error?

I'm building a form management program but right now I'm just trying to build a queue system to handle all the forms when they're assigned to someone.
when I call this first function, it should populate the elements of the activeWork array by pulling from each collection that the entries reference, there are several collections that could be referenced in active work, so I'm trying to use the collection type field to determine what collection to pull from, I don't know if I formatted any of this correctly because its my first time building any of this.
import statesPersons from "./statesPersons.schema.js";
export async function getStatesPersonsActiveWorkByProfileId(req, res){
try{
const { profileId } = req.params
const data = await statesPersons.find({profileId})
.populate('statesPersons.activeWork.referenceId')
return res.send({
message: "success",
data: data,
status: 200 })
}catch(e) {
console.error(e.message)
return res.send({
message: "couldn't fetch active work",
data: null,
status: 500 })
}
}
Here is the schema for statesPersons, the collection where active work is stored.
import mongoose, {model, Schema} from "mongoose";
const activeWorkSchema = new Schema({
active: Boolean,
collectionType: {
type: String,
enum: ['messages'],
},
referenceId: {
type: Schema.Types.ObjectId,
refPath: "statesPersons.activeWork.collectionType"
},
sentBy: {
type: Schema.Types.String,
ref: "statesPerson",
},
sentTo: {
type: Schema.Types.String,
ref: "statesPerson",
},
timeRecived: Date,
dueDate: Date,
subject: String,
viewed: Boolean,
content: {},
})
const statesPersonsSchema = new Schema({
profileId:{
type: String,
required: true,
unique: true
},
department: {
type: String,
required: true,
index: true,
},
firstName: String,
lastName: String,
location: String,
org: String,
title: String,
jobDescription: String,
email: {
type: String,
lowercase: true,
},
phoneNumber: String,
activeWork: [activeWorkSchema],
emailList: [String],
jobAssignments: [String],
affiantInfo: {
affiantInfoTitle: String,
affiantInfoExperience: String,
},
assessments: [
{
assessdBy: {
type: Schema.Types.ObjectId,
ref: "statesPerson",
},
dueDate: Date,
questions: {},
},
],
});
export default mongoose.model("statesPersons", statesPersonsSchema);
When I make a query, I get:
Cannot populate path statesPersons.activeWork.referenceId because it is not in your schema. Set the strictPopulate option to false to override.
I don't know if I formatted my populate correctly or if the problem is in my schema,

how to make a dynamic form creation and response mangement system like google forms work?

I was working on a project where we can create a form like google forms and get responses from users, and then we can view those responses in the admin panel.
My English is not that good I tried my best to explain the problem!
I am using MERN Stack so I was tucked into a problem related to how to save the questions and record the responses in MongoDB in a standard way in objects and arrays.
currently I added this as a form model :
const formSchema = new Schema({
usererId: { type: Schema.Types.ObjectId, ref: 'User' },
title: { type: String, required: true },
description: { type: String},
username: { type: String, required: true },
password: { type: String, required: true },
isEnabled: { type: Boolean, default: true },
expiresOn: { type: Date, default: null },
fields: [
{
title: { type: String, required: true },
placeholder: { type: String, required: false },
type: { type: String, required: true },
required: { type: Boolean, required: true },
options: [
{
title: { type: Object, required: true },
priority: { type: Number, default: 0, required: true }
}
],
priority: { type: Number, required: true, default: 0 },
enabled: { type: Boolean, default: true, required: true }
}
],
}, {
timestamps: true
})
and form responses :
const formResponseSchema = new Schema({
digitalFormId: { type: Schema.Types.ObjectId, ref: 'Form' },
isVerified: { type: Boolean, default: false },
formResponse: [{ type: Object, required: true }],
}, {
timestamps: true
})
I don't know if this approach is good, I myself like it's not like a standard one and I m confused, Someone please tell me how should I do it and what is the perfect way of doing it,
If you have a problem understanding what I am saying just tell me simply how a google form works in the backend from API view, like question ID server-side validation and response submit, that time what type of request is sent to the server, something like this !
If you don't mind please take out some time and write a brief approach of what type of Schema should I use and how should I save them.
Something more important is what approach to use while checking the form response data coming from the client to validate on server-side means on express API, like {questionId: idofquestion, value:'Value of the response of the particular question'}, later checking the question label and all other things with the form questions and all validation rules to fetch from them and check, but I don't know how to do that It's really confusing for me.
Thanks in Advance for the help! ❤️

Like - unlike system in MongoDb to find if user liked or not?

I'm trying to make a middleware for cheaking if user already liked the post for a React-toggle on click I've achieved a pretty good way in it in front end which i'm able to find weather user liked the post or not then toggle the button, the problem is i'm trying to match it in backend side to cheak if the likes array in schema already has the userId or not
the middleware be like
exports.liked = async (req, res, next) => {
const Liked = await Post.find( { likes : { $elemMatch: req.body.userId } } )
if (Liked){
return res.status(400).json({
error: "AlreadyLiked",
})} else {next()}
};
my mongoose schema is
let postSchema = new mongoose.Schema({
title: {
type: String,
minlength: 4,
maxength: 150,
},
body: {
type: String,
required: "Body is required",
minLength: 1,
maxLength: 2500,
},
photo: {
data: Buffer,
contentType: String,
},
postedBy: {
type: ObjectId,
ref: "User",
},
created: {
type: Date,
default: Date.now,
},likes: [{ type: ObjectId, ref: "User" }]
});
I aprreciate helps, thanks in first :)

Mongoose schema for storing an array of JSON objects for subdocuments

I have a JSON object that I want to create a schema for using mongoose
{ ProjectName: 'asdf',
Embargo: 'Yes',
Angle: '1',
Facts: '[{"count":1,"fact":"dsafdsaf","content":"dsafdsaf"}, {"count":3,"fact":"dsafdsaf","content":"dsafdsaf" } , {"count":2,"fact":"dsafdsaf","content":"dsafdsaf"}]',
About: '<p>Anthony Bodin </p>',
EditorNote: 'No',
OrderId: 'tok_14kGRO2Jju1nvjb47YF9jQTJ',
Payment: 'Paid' }
My problem is that the Facts element will contain and array of objects and I am not quite sure how to save it into the database as
Here is the schema that I have right now
var ArticleSchema = new mongoose.Schema({
userId: {
type: String,
default: ''
},
userEmail: {
type: String,
default: ''
},
article: {
date: {
type: Date,
default: Date()
},
ProjectName: {
type: String,
default: ''
},
Embargo: {
type: String,
default: true
},
Angle: {
type: String,
default: ''
},
Facts: {
type:Array
},
About: {
type:String,
default:''
},
EditorNote: {
type:String,
default:''
},
Payment: {
type: String,
default: 'Not Paid'
},
OrderId: {
type:String,
default:''
}
}
});
Is saving the data as an array the right way to save the Facts element ?
Its very simple. Just make facts an array.
So change
Facts: {
type:Array
},
to Facts: [] and it will be able to store the array of objects you have there in the Facts json field.

Resources