I am trying to delete a MongoDB document after 5 minutes but it deleted almost after 2 min. I exactly don't know the issue. Any help is highly appreciated.
const hospitalRecordSchema = new mongoose.Schema({
hospital_id: {
type: String,
},
hospital_name: {
type: String,
},
created_at: {
type: Date,
default: new Date(),
expires: "5m",
index: true,
},
data: {
type: Object,
default: {},
},
});
hospitalRecordSchema.index({ created_at: 1 }, { expireAfterSeconds: 300 });
module.exports = mongoose.model("HospitalRecord", hospitalRecordSchema);
Related
const mongoose = require("mongoose");
const expirationTime=10
let currentTime = Date.now();
const userSchema = new mongoose.Schema(
{
fullName: {
type: String,
required: false,
},
email: {
type: String,
required: false,
},
mobile_number: {
type: String,
required: false,
},
password: {
type: String,
required: false,
},
otp_instance: [{
otp_id: {
type: mongoose.Schema.Types.ObjectId,
required: false
},
otp: {
type: String,
// index: {expires:'1m'},
required: false
},
createdAt: {
type: Date,
default: Date()
},
expiration_time: {
type: Date,
default: new Date(currentTime+(expirationTime * 1000))
},
// otp: { type: String, index: { expires: 300 }}
}],
resetLink: {
type: String,
required: false,
},
isAccountVerified: {
type: String,
required: false,
},
token: {
type: String,
required: false,
},
activeStatus: {
type: String,
required: false,
default: "0",
},
deletedStatus: {
type: String,
required: false,
default: "0",
},
},
{ timestamps: true }
);
// userSchema.createIndex( { otp: 1 }, { expireAfterSeconds: 36000 } )
const userModel = mongoose.model("user", userSchema);
module.exports = userModel;
is it possible to expire in 1 min in model of particular data like stored otp in mongodb
is it possible to expire in 1 min in model of particular data like stored otp in mongodb
is it possible to expire in 1 min in model of particular data like stored otp in mongodb> is it possible to expire in 1 min in model of particular data like stored otp in mongodb> is it possible to expire in 1 min in model of particular data like stored otp in mongodb> is it possible to expire in 1 min in model of particular data like stored otp in mongodb> is it possible to expire in 1 min in model of particular data like stored otp in mongodb
I building a calendar app with React & Express.js & Mongo DB
the calendar has month view displays weekly events, and i want to delete these events automaticlly after 30 days
my schema.ts:
import { Calendar } from "../types";
const calendarSchema = new mongoose.Schema<Calendar>(
{
startDate: {
type: String,
required: true,
},
endDate: {
type: String,
required: true,
},
rRule: {
type: String,
},
title: {
type: String,
required: true,
},
notes: {
type: String,
// required: true,
},
type: {
type: String,
required: true,
},
expireAt: {
type: Number,
},
},
{
timestamps: true,
}
);
calendarSchema.index({ expireAt: 1 }, { expireAfterSeconds: 70 });
export default mongoose.model<Calendar>("Calendar", calendarSchema);
and i am creating a "expireAt" field in my front-end like:
const payload = await createAppointment({
...appointment,
expireAt: new Date().getTime() + 80,
});
now this deletes documents in 40 - 50 seconds, my question is how can i make it 30 or 31 days ?
thanks in advance .
Change expireAt to Date instead of number
And when creating an index assign 0 to expireAfterSeconds
calendarSchema.index({ expireAt: 1 }, { expireAfterSeconds: 0 });
Now you can define the exact date of when each Calendar will expire, from yearly or down back to seconds
For more info, check MongoDB's documentation
The issue is that you set expiry to be after 70 seconds:
calendarSchema.index({ expireAt: 1 }, { expireAfterSeconds: 70 });
Instead of 70 in the expireAfterSeconds just push the value you want, for example for 7 days:
60 * 60 * 24 * 7 = 604800
Hello devs. Without further ado...
I have a problem updating a column in the database. When performing an update on a column it is multiplying the data. It doesn't make any sense since the multiplied data contains the same _id. And that _id is a unique value.
Here is a part of the code that contains the query:
const addressId = await new Promise(async function(resolve, reject) {
await Cadastros.updateOne({_id: user_id}, {$push: {enderecos: endereco}}, (err, raw) => {
if(err){
if(!err._id) return reject(false);
if(err._id) return resolve(err._id);
}
return resolve(false);
});
})
This algorithm is responsible for adding a new address to the user's registration in the database using the $push method.
Follows the Schema JSON:
{
cpf: {
type: String,
required: true,
unique: true
},
email: {
type: String,
unique: true,
required: true,
max: 100,
lowercase: true
},
senha: {
type: String,
max: 100
},
nome_completo: {
type: String,
max: 100
},
data_de_nascimento: {
type: Date
},
sexo: {
type: String,
default: null
},
enderecos: [
{
nome_completo: {
type: String
},
cep: {
type: Number
},
endereco: {
type: String,
max: 60
},
num: {
type: Number
},
bairro: {
type: String,
max: 60
},
cidade: {
type: String,
max: 30
},
estado: {
type: String,
max: 2
},
complemento: {
type: String,
max: 21,
default: ""
},
referencia_end: {
type: String,
max: 60,
default: null
},
celular: {
type: Number
},
principal:{
type: Boolean,
default: false,
}
}
],
ip: {
type: String,
max: 45
},
user_agent: {
type: String
},
fingerprint: {
type: String
},
device_info: {
type: String
},
exists: {
type: Boolean,
default: false
},
data_criacao: {
type: Date,
default: Date.now()
}
}
It is also the only middleware in the same table:
CadastrosSchema.post('updateOne', async function(doc, next){
const data = this.getUpdate();
if(data.$push ? data.$push.enderecos : false) return next({_id: data.$push.enderecos._id})
next()
})
And the middleware part was a workaround, but it was the only way I found to return the _id generated from the added subdocument.
Here is the multiplied subdocument:
There are two subdocuments with the same _id. It didn't make any sense to me.
Anyone who knows what is going on and can bring a solution is grateful. There may also be other people with the same problem, so that would help not only me but other people. If there's a problem with that code, I can't see it.
Change $push for $addToSet solved my problem.
I am trying to set a TTL via mongoose when a document is created in MongoDB, but I'm not having any luck with any of my attempts. Latest version of mongoose is being used in my project and from what I can tell I've tried the most common answers here on SO and elsewhere online.
My Schema
const mongoose = require('mongoose');
const jobSchema = new mongoose.Schema(
{
positionTitle: {
type: String,
},
description: {
type: String,
}
});
const Jobs = mongoose.model('job', jobSchema);
module.exports = Jobs;
I have tried adding a createdAt with expires based on this question answer:
const jobSchema = new mongoose.Schema({
positionTitle: {
type: String,
},
description: {
type: String,
},
createdAt: { type: Date, expires: 3600 },
});
Along with this option that's also in the same question to have createdAt be created automatically via timestamps:
const jobSchema = new mongoose.Schema(
{
positionTitle: {
type: String,
},
description: {
type: String,
},
},
{ timestamps: true }
);
Trying variations of the following to set an index with timestamps defined:
jobSchema.index({ createdAt: 1 }, { expires: 86400 });
jobSchema.index({ createdAt: 1 }, { expires: '1 day' });
jobSchema.index({ createdAt: 1 }, { expireAfterSeconds: 3600 });
Regardless of which option I try, the document is removed after MongoDB's 60-second cycle when a createdAt field is set on the document. Would really love to know what I'm doing wrong.
After trying all the solutions in the thread you mentioned, none of them worked. In the end this code did the trick. It involves setting the expireAt field to the actual time that you want it deleted, which makes sense really.
const Schema = mongoose.Schema;
const YourSchema = new Schema({
expireAt: {
type: Date,
default: Date.now() + 10 * 60 * 1000 // expires in 10 minutes
},
});
This is the only thing that worked, all the other solutions I tried always deleted after 1min, no matter the amount of time I added.
I've been having issues with this as well. I found this thread here https://github.com/Automattic/mongoose/issues/2459 and it worked for me. Translated into your code would look like this.
const mongoose = require('mongoose');
const jobSchema = new mongoose.Schema(
{
positionTitle: {
type: String,
},
description: {
type: String,
},
expireAt: {
type: Date,
default: Date.now,
index: { expires: '5s' }
}
});
const Jobs = mongoose.model('job', jobSchema);
module.exports = Jobs;
On the link I added, it is the very last solution. I'm not exactly sure what this is doing but here is the mongo link of what it should be doing for anyone else with this issue. https://docs.mongodb.com/manual/tutorial/expire-data/. To change the amount of time that you need the document just change the expires. It accepts '#s' and '#d' for sure. Also if you want your document to be deleted at a specific time then you can do this.
expireAt: {
type: Date,
default: new Date('July 22, 2013 14:00:00'),
index: { expires: '0s' }
}
This will delete the document 0 seconds after the specified date.
Problem in TTL, Reason behind Document does not delete after some / few seconds, how to expire document in MongoDB / Mongoose using schema. Solution expireAfterSeconds / expires / index.
NOTE: - MongoDB's data expiration task runs once a minute, so an expired doc might persist up to a minute past its expiration. This feature requires MongoDB 2.2 or later. It's up to you to set createdAt to the current time when creating docs or add a default to do it for you as suggested here.
NOTE :- Below code is working fine and the document will delete after 5 minutes.
const verficationSchema = new mongoose.Schema({
email: {
type: String,
required: true,
unique: true,
lowercase: true,
trim: true,
validate(email) {
if (!validator.isEmail(email)) {
throw new Error("Email is not valid!");
}
},
},
otp: {
type: Number,
required : true
},
expireAt : {
type: Date,
default: Date,
expires : 300 // means 300 seconds = 5 minutes
}
});
NOTE :- Upper code is working fine, But document will delete after 1 minutes, because MongoDB check expiration procedure after every 1 minutes.
const verficationSchema = new mongoose.Schema({
email: {
type: String,
required: true,
unique: true,
lowercase: true,
trim: true,
validate(email) {
if (!validator.isEmail(email)) {
throw new Error("Email is not valid!");
}
},
},
otp: {
type: Number,
required : true
},
expireAt : {
type: Date,
default: Date,
expires : 8 // means 8 seconds
}
});
I wanna fetch all users who has most sparks in last 7 days
Sparks are something like friends
can anyone help in this problem
Thanks in advance
//create schema for users
const UserSchema = new Schema({
password: {
type: String,
default: "",
},
account_type: {
type: String,
default: "",
},
account_name: {
type: String,
default: "",
},
firstName: {
type: String,
default: "",
},
lastName: {
type: String,
default: "",
},
image: {
type: String,
default: "",
},
sparks: [
{
user: {
type: Schema.Types.ObjectId,
ref: "users",
},
status: {
type: Number,
required: true,
enum: STATUS,
},
createdAt: {
type: Date,
default: Date.now,
},
},
],
createdAt: {
type: Date,
default: Date.now,
},
});
This is my schema
router.get("/leaderboard/get/sparks", async (req, res) => {
let newDate = moment().subtract(7, "day");
console.log(
Date("2020-06-26T12:49:29.324Z") < Date("2020-06-24T12:49:29.563+00:00")
);
let topUsers = await User.aggregate([
{
$match: {
"sparks.createdAt": { $eq: new Date("2020-06-24T12:49:29.563+00:00") },
},
},
]);
res.status(200).json({ date: topUsers });
});
This is what I tried but did not work for me
I tried so many ways but faild
I was searching but not found anthing useful for my problem
You can do the following aggreagtion
User.aggregate([
{
'$project': {
'_id': 1,
'numberOfSparks': {
'$cond': {
'if': {
'$isArray': '$sparks'
},
'then': {
'$size': '$sparks'
},
'else': 'NA'
}
}
}
}, {
'$sort': {
'numberOfSparks': -1 //sort in descending order
}
}, {
'$limit': 10 // get top 10 users
}
])
Now this will work fine but if this aggregation is used frequently I would advice you a different approach. Aggregation is quite compute intensive it has to check all the users, then generate all the computed field, numberOfSparks, then sort. So as the number of users and sparks grow it could slow your server down.
Instead you could make a sparkCount field in your user schema. Then every time a spark is pushed to your User, you could increment a sparkCount field. Simply index the sparkCount field. Now you can easily query users with top sparkCount with a single query;
User.find({}).sort({sparkCount:-1}).limit(10)
This query will only read the 10 user documents with top sparkCount. No additional computation. And its also very scalable. Number of users and sparks will not effect performance.
Hope it helped