I want to delete a particular task document automatically. createdAt: {type: Date} => it will take future date and time, and duration:{type: String} => it will take time in hours. whenever the future time arrives from that time to next how much duration we insert, after completion of duration the task document will delete
const mongoose = require('mongoose')
const TaskSchema = new mongoose.Schema({
taskName: { type: String, required: true },
description: { type: String },
creator: { type: String },
duration: { type: String },
createdAt: {type: Date}
})
const Tasks = mongoose.model('Task', TaskSchema)
module.exports = Tasks```
**Please help how to approach this task**
try this
const TestSchema = new Schema({
expire_at: {type: Date, default: Date.now, expires: "your desired value"}
})
this is the solution you are looking for here
Related
Before everyone tells me I can't call a const before initializing, I do know that.
But I think this is the simplest way to render the concept I have in mind, (where any subdocument within the replies array also has the same schema as the parent, and documents within the replies array of those subdocuments also having the same schema). I would really appreciate anyone's input.
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
var commentSchema = new mongoose.Schema({
content: String,
createdAt: {
type: Date,
default: Date.now
},
score: {
type: Number,
default: 1
},
username: {
type: String,
lowercase: true
},
parent: {
type: Schema.Types.ObjectId,
ref: 'comment'
},
replyingTo: String,
replies: [commentSchema]
});
module.exports = mongoose.model("comment", commentSchema);
Since a const can't be called before initialization, to fix this issue the parent schema should be called on the children array after initialization the code below:
commentSchema.add({ replies: [commentSchema] })
The final result should look like this:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const commentSchema = new mongoose.Schema({
content: String,
createdAt: {
type: Date,
default: Date.now
},
score: {
type: Number,
default: 1
},
username: {
type: String,
lowercase: true
},
parent: {
type: Schema.Types.ObjectId,
ref: 'comment'
},
replyingTo: String,
});
commentSchema.add({ replies: [commentSchema] })
I am trying to save the localtime as default when creating an item in mongoose
const ItemSchema = new mongoose.Schema({
item_name: { type: String, required: true },
shop_id: { type: mongoose.Schema.Types.ObjectId, ref: "Shop" },
createTime: { type: Date, default: moment().utcOffset(7) },
});
As you can see I am trying to offset the moment utc time but it is not working? What am I doing wrong?
You're just passing the moment instance to your createTime field and that won't work. After you use .utcOffset() to convert the date to your local time zone, you need to extract it as something that can be understood by mongoose as a date. According to the momentjs doccumentation, the fix should be as easy as adding .format() yo your moment object: moment().utcOffset(7).format().
moment() dose not return a new Date()
mongoose schema expects a Date instance
Try:
const ItemSchema = new mongoose.Schema({
item_name: { type: String, required: true },
shop_id: { type: mongoose.Schema.Types.ObjectId, ref: "Shop" },
createTime: { type: Date, default: new Date(moment().utcOffset(7).format()) },
});
How Can we change the value of updated_at whenever Data of DB is updated
Consider this to be my Mongoose Schema,
const mongoose = require('mongoose')
const locationDataSchema = new mongoose.Schema({
locationName: String,
location: [{
lat: Number,
lng: Number
}],
news: [ {
author: String, //or number
title: String,
description: String,
url: String,
urlToImage: String
}],
updated_at: {
type: Date,
default: Date.now
}
})
From my Vaguely reading of Mongoose Docs, I did something like this
locationDataSchema.post('save', (next) => {
console.log("here")
this.locationName = this.locationName.toLowerCase();
this.updated_at = Date.now()
})
But this isn't being called whenever I create/update something in my mongoose Schema
Question: Can someone help me in figuring out how can I change
updated_at = Date.now()
Whenever user updates data in DB (similarly changing location Name to Lowercase)
The current version of Mongoose (v4.x) has time stamping as a built-in option to a schema:
var mySchema = new mongoose.Schema( {name: String}, {timestamps: true} );
This option adds createdAt and updatedAt properties that are timestamped with a Date, and which does all the work for you.
For more please look at
https://mongoosejs.com/docs/guide.html#timestamps
I have created this schema for user registration:
let userSchema = new mongoose.Schema({
lname: String,
fname: String,
username: String,
email: String,
password: String,
registrationDate: {
type: Date,
default: Date.now()
},
referedBy: {
type: String,
default: ''
},
referalEnd: {
type: Date,
default: Date.now() + 5*365*24*60*60*1000
},
userRefererId: {
type: String,
default: uniqid()
}
});
As you can see, there is a Date.now function and uniqid function in the schema.
Those functions can be used approximately once every 5 minutes,
because if I create two users a few seconds apart, it generates the same uniqid and shows the same date.
Remove the () from Date.now() and just call Date.now.
I've run into this before, the schema is generated at deployment / start time and not regenerated on each new creation hence why the time is always the same. Its better to generate the date / time outside the new Model().save() call.
let userSchema = new mongoose.Schema({
lname: String,
fname:String,
username: String,
email: String,
password: String,
registrationDate: {
type: Date,
default: function(){return Date.now()}
},
referedBy: {
type:String,
default: ''
},
referalEnd: {
type: Date,
default: function(){ return Date.now() + 5*365*24*60*60*1000}
},
userRefererId: {
type:String,
default: uniqid()
}
});
Hi, I am trying to return my query in backwards order from which it was created.
The docs are a little unclear on how to use the sort method:
http://mongoosejs.com/docs/api.html#types_array_MongooseArray.sort
Here is my schema:
const mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.Types.ObjectId;
let PostSchema = new Schema({
title : String,
description: String,
image : String,
tags : [String],
original_poster: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
date: {
type: Date,
default: new Date()
}
})
module.exports = mongoose.model('Post',PostSchema);
I have run,
db.posts.find().sort({date:-1}).pretty()
For example, if my model was a 'Post' model and my first post was 'hello world' and my second post was 'this is a post'. I would like to see:
['this is a post', 'hello world']
However, what I am actually seeing is ['hello world','this is a post']
Figured out the answer
in posts schema add:
date: {
type: Date,
default: Date.now
}
then db.posts.find().sort({date:-1}).pretty() will yield the posts sorted from most recent to least recent
You have to add a creation timestamp in your schema and sort by its key.
let PostSchema = new Schema({
title : String,
description: String,
date : Date, // Here is your date
image : String,
tags : [String],
original_poster: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
}
})
and when you insert a document, use:
date: new Date()