Remove MongoDB documents that are more than 6 months old - javascript

I’m using Mongoose to connect with my MongoDb cluster.
My site has a logging feature. I would like these logs to deleted once they are 6 months old. To do this, I have a file that runs every day to delete documents that are more than 6 months old.
However, the deleteMany() function does not provide me with context to run a function on each document, only that every document has a specific value.
Dates are stored as numbers (shown below)
const mongoose = require('mongoose');
let Sch = new mongoose.Schema( {
id: {
type: String,
default: '',
required: true,
},
password: {
type: String,
default: '',
required: true
},
email: {
type: String,
default: '',
required: true
},
first_name: {
type: String,
required: true,
default: 'John'
},
last_name: {
type: String,
required: true,
default: 'Doe'
},
username: {
type: String,
default: '',
required: true
},
seven_shifts: {
type: Object,
default: {},
},
positouch: {
type: Array,
default: {}
},
departments: {
type: Array,
default: [],
required: true
},
locations: {
type: Array,
default: [],
required: true
},
tip_periods: {
type: Array,
default: []
},
w_4: {
type: String,
default: ''
},
employedSince: {
type: Number
},
notes: {
type: Array,
default: []
},
last_login: {
type: Number
},
});
module.exports = new mongoose.model('User', Sch, 'users');
All I need is a way to check if the number in "date" is less than the one I provide in the function
Does anybody know of a way I can delete the matching documents in one query?
Thanks.

Related

How to print Mongoose object properties with console.log?

These are the schema from mongoose subdocuments example.
let classTypeSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
abilities: {
type: Array,
default: []
},
skills: {
type: Array,
default: []
}
});
let heroSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
minlength: 3,
maxlength: 24
},
classType: [classTypeSchema],
level: {
type: Number,
default: 1
},
currency: {
type: Number,
default: 0
}
});
I tried this way
Hero = mongoose.model('Hero',heroSchema);
console.log(typeof Hero);
console.log(JSON.stringify(Hero, null, 4));
Output
function
undefined
Console.dir gives very detailed output.I am interested only in schemas part
subpaths: {
'classType.name': [SchemaString],
'classType.abilities': [SchemaArray],
'classType.skills': [SchemaArray],
'classType._id': [ObjectId],
'classType.abilities.$': [Mixed],
'classType.skills.$': [Mixed]
},
Is there any other way to print Mongoose properties and methods?

findByIdAndUpdate keeps being caught in .catch

So when I am executing my findByIdAndUpdate it doesn't execute my promise as expected and goes into my catch. I sent responses to postman and using res.json(req.user.id) and res.json(profileFields) . This is the response I get when I use
profileFields
{
"user": "5b3134a0e2543b06d130a5d7",
"handle": "wadeaston1",
"status": "Developer",
"skills": [
"HTML",
" CSS",
" Javascipt"
],
"social": {}
}
i'm at a loss here because all my fields are passing in the values as expected into user and $set. I don't understand why its going to my catch
Profile.findByIdAndUpdate(
{ user: req.user.id },
{ $set: profileFields },
{ new: true }
)
.then(profile => res.json(profile))
.catch(err => {
res.json("Timeout");
console.log("HI");
});
Here is my Profile Schema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
//Create Scheme
const ProfileSchema = new Schema({
user: {
//this will associate user by their ID
type: Schema.Types.ObjectId,
ref: "users"
},
handle: {
type: String,
required: true,
max: 40
},
company: {
type: String
},
website: {
type: String
},
location: {
type: String
},
status: {
type: String,
required: true
},
skills: {
//Array of strings
type: [String],
required: true
},
bio: {
type: String
},
githubusername: {
type: String
},
experience: [
{
title: {
type: String,
required: true
},
company: {
type: String,
required: true
},
location: {
type: String
},
from: {
type: Date,
required: true
},
to: {
type: Date,
required: true
},
current: {
type: Boolean,
default: false
},
description: {
type: String
}
}
],
education: [
{
school: {
type: String,
required: true
},
degree: {
type: String,
required: true
},
fieldofstudy: {
type: String,
required: true
},
from: {
type: Date,
required: true
},
to: {
type: Date,
required: true
},
current: {
type: Boolean,
default: false
},
description: {
type: String
}
}
],
social: {
youtube: {
type: String
},
twitter: {
type: String
},
facebook: {
type: String
},
linkedin: {
type: String
},
instagram: {
type: String
}
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Profile = mongoose.model("profile", ProfileSchema);
findByIdAndUpdate is for finding the document to update by its _id value, but you need to find the document by its user field, so you should be using findOneAndUpdate instead:
Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFields },
{ new: true }
)
.then(...
No need to manually cast req.user.id to an ObjectId as Mongoose will do that for you based on the way user is defined in your schema.
Based on the error you gave, it looks like you need to turn req.user.id from a string to an ObjectId:
Profile.findByIdAndUpdate(
{ user: new mongoose.Types.ObjectId(req.user.id) },
{ $set: profileFields },
{ new: true }
).then( /* rest of code */
This assumes you did a const mongoose = require('mongoose') or similar.

Mongodb in array query wont get any result

Okay, so im getting all convensations with the following query:
return convensations.findOne({}).lean().then(function (convensations) {
console.log(convensations);
});
that would results in the following:
{ _id: 598dd4458b08b727dc53d4a6,
initiateduser: 'spillinfo',
gang: false,
global: false,
members: [ 'spillinfo', '59312d2b329b7535b07e273c' ],
name: 'no name',
__v: 0 }
thats totally fine, but when i do
var userid = "59312d2b329b7535b07e273c";
return convensations.find({members: userid}).lean().then(function (convensations) {
console.log(convensations);
});
it wont get me any results, why is that?
what im i doing wrong to check if the userid is within the members array?
UPDATE EDIT:
DB schema:
new Schema({
initiateduser : String,
name: {type:String, default: 'no name'},
members: { type: Array, default: []},
time: Number,
global: { type: Boolean, default: false},
gang: { type: Boolean, default: false},
});
and example of inserting / creating new:
var conv = new convensations();
conv.members = [userid, user2];
conv.initiateduser = userid;
conv.save(function (err,room) {
edit2:
some debug from query:
getting convensations with userid 59312d2b329b7535b07e273c
Mongoose: convensations.find({ members: ObjectId("59312d2b329b7535b07e273c") }, { fields: {} })
convensations: 0
Change your schema as,
new Schema({
initiateduser : String,
name: {type:String, default: 'no name'},
members: { type: [String], default: []},
time: Number,
global: { type: Boolean, default: false},
gang: { type: Boolean, default: false},
});

mongooseJS return number of IDs in a collection

I'm using mongooseJS as a mongoDB driver in Javascript. I can return the number of fields in the database with the following code:
app.get('/total/', (req, res) => {
var id = req.params.id;
boxmac.count().then((macdb) => {
res.send({macdb});
}, (e) => {
res.status(404).send(e)
console.log(e);
});
});
Which when I load the file with node, and query the resulting link, I get
{
"macdb": 2108
}
However I'm trying to return the number of Unique ID's in the collection (should be 168-170). I've tried placing the id in various places (such as count({id}).then, but can't get the number of ID's.
here's my model:
var boxmac = mongoose.model('macdbs', {
ProductName: {
type: String,
required: true,
minlength: 1,
trim: true
},
OriginCountry: {
type: String,
default: false
},
StoreBrand: {
type: String,
default: null
},
Type: {
type: String,
default: null,
required: true
},
Pasta: {
type: String,
default: null,
required: false
},
ADC: {
type: String,
default: null,
required: false
},
PastaType: {
type: String,
default: null,
required: false
},
Org: {
type: String,
default: 'N',
required: false
},
Veg: {
type: String,
default: 'N',
required: false
},
Mic: {
type: String,
default: null,
required: false
},
Exp: {
type: String,
default: null,
required: false
},
PriceRaw: {
type: String,
default: null,
required: false
},
SauceType: {
type: String,
default: 'dry',
required: true
},
BoxSize: {
type: String,
default: null,
required: true
},
EpNo: {
type: Number,
default: null,
required: true
},
URL: {
type: String,
default: null,
required: true
},
Price: {
type: String,
default: null,
required: true
},
Rating: {
type: String,
default: null,
required: false
},
Comments: {
type: String,
default: null,
required: false
}
});

How to update User object by pushing a schema ref to a User's array field

My user schema has an array of Notifcation objects. I would like to find a user by their email and then update the user's notifications field by adding a new notification object. The code I have right now doesn't return an error but it also doesn't update the user's notification field with new notification.
var notification = { type: data.notification_type, from: socket.request.user._id };
notification = new Notification(notification);
User.update({ email: data.to }, { $push: { notifications: notification } }, function(err, model) {
if (err) console.log(err);
});
User Schema
var UserSchema = new Schema({
firstName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
organization: {
type: String,
trim: true,
default: '',
required: 'Please fill in an organization name'
},
position: {
type: String,
trim: true,
default: '',
required: 'Please fill in the title of your position'
},
displayName: {
type: String,
trim: true
},
email: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your email'],
match: [/.+\#.+\..+/, 'Please fill a valid email address']
},
username: {
type: String,
unique: 'testing error message',
required: 'Please fill in a username',
trim: true
},
password: {
type: String,
default: '',
validate: [validateLocalStrategyPassword, 'Password should be longer']
},
salt: {
type: String
},
provider: {
type: String,
required: 'Provider is required'
},
providerData: {},
additionalProvidersData: {},
roles: {
type: [{
type: String,
enum: ['user', 'admin']
}],
default: ['user']
},
updated: {
type: Date
},
created: {
type: Date,
default: Date.now
},
/* For reset password */
resetPasswordToken: {
type: String
},
resetPasswordExpires: {
type: Date
},
notifications: [{
type: Schema.ObjectId,
ref: 'Notifcation'
}]
});
you can use findOneAndUpdate instead of just update . first you have to find using your condition and then push your notification .i hope this help's
var notification = { type: data.notification_type, from: socket.request.user._id };
notification = new Notification(notification);
User.findOneAndUpdate(
{ email: data.to },
{ $push:
{ notifications: notification }
},
function(err, model) {
if (err) console.log(err);
});

Categories