How to convert the momentJs time to local time - node.js

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()) },
});

Related

How to delete a particular document automatically in mongodb in nodejs

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

Is there any other method for deleting a data in mongoose after a given time

const notificationSchema = mongoose.Schema({
type:{
type: String
},
message:{
type: String
},
userId:{
type: String,
required: true,
},
timestamp:{
type: Date,
default: new Date()
},
expireAt: {
type: Date,
default: Date.now,
index: { expires: '5m' },
},
})
My data is not getting automatically delete in mongoose, Is something wrong with my model? Here is my Structure of model.Can anyone help
const notificationSchema = mongoose.Schema({
type:{
type: String
},
message:{
type: String
},
userId:{
type: String,
required: true,
},
{
timestamps: true
}
});
notificationSchema.index({createdAt: 1},{expireAfterSeconds: 3600});
Each field in the collection will be deleted after 3600seconds
There's several ways, but one that pops to mind is TTL.
"TTL indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time or at a specific clock time."
Find out more here > https://docs.mongodb.com/manual/core/index-ttl/
And for mongoose > https://github.com/mongoosejs/mongoose-ttl

How to index mongoose-timestamp in elastic search

We have a mongoose object with schema like following, with the use of timestamps, we are populating createdAt & updatedAt fields. We are using mongoosastic to index these in elastic search.
var mongoose = require("mongoose");
var employeeSchema = new mongoose.Schema(
{
name: {
type: String
es_indexed: true,
es_index:"analyzed"
},
managerId: {type: mongoose.Schema.Types.ObjectId},
details:{},
email: {
type: String
es_indexed: true,
es_index:"analyzed"
},
phone: {
type: Number
es_indexed: true,
es_index:"analyzed"
}
},
{
timestamps: true
});
I want to index updatedAt as well in elastic search, but not sure how to do it with mongoosastic. Please let me know are these specific option to get this done.
Have you tried mapping the date as per the docs?
So, something like
var ExampleSchema = new Schema({
// Date (core type)
createdAt: {type:Date, es_type:'date', es_indexed: true},
updatedAt: {type:Date, es_type:'date', es_indexed: true}
},
{ timestamps: true }
)

How to compare _id value of Models made using Mongoose?

I have the following two schemas of User and Critique and I've got the data persisted in MongoDB database:
var userSchema = mongoose.Schema({
critiques: [{ type: Schema.ObjectId, ref: 'Critique' }],
});
var User = mongoose.model("User", userSchema);
var critiqueSchema = mongoose.Schema({
author: {type: String, default: ''},
date: { type: Date, default: Date.now },
comment: { type: String, default: '' },
stars: { type: Number, default: 0 },
_user: { type: Schema.ObjectId, ref: 'User' }
});
var Critique = mongoose.model("Critique", critiqueSchema);
user.critiques[0]._id.equals(critique._id) is giving me undefined is not a function.
How to compare _id value of a User instance with the Critique instance?
The critiques field of your user object directly contains an array of ObjectIds, so it would just be:
user.critiques[0].equals(critique._id)
user.critiques would only contain full Critique objects if you chained a .populate('critiques') call in the find where you obtained user.

Adding an array inside my Mongoose schema

I have the following schema where I am trying to add an array of comments to my blog post schema, then inside the comments schema I need to add an array of pictures urls related to each specific comment. I've researched the web and found this link embedded documents to mongoose documentation, yet noticed that it is related to mongoose version 2.7 while we are currently at version 3.8. So was wondering if I am doing it right?, and if not can someone please help me by suggesting the best way for designing my blog post schema so that it includes the blog post array of comments as well as the array of pictures related to each comment. Thanks for your time and effort.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var pictures = new Schema({
picURL: String,
date: {
type: Date,
default: Date.now
}
});
var comments = new Schema({
subject: String,
body: String,
date: {
type: Date,
default: Date.now
},
pictures:[pictures]
});
var blogpost = new Schema({
title: String,
body: String,
date: {
type: Date,
default: Date.now
},
comments:[comments]
});
module.exports = mongoose.model('BlogPost', blogpost);
you have two common scenarios here how you would like to handle your information
Embedded document:
if you are likely to do more reads than writes it's recommended to follow this approach in this case your model could be like this:
var comments = new Schema({
subject: String,
body: String,
date: {
type: Date,
default: Date.now
},
pictures:[{
picURL: String,
date: {
type: Date,
default: Date.now
}
}]
});
and also your approach to me is ok and should run on 3.8 without potential issues.
Referenced document:
if you'll have more writes than reads you can different collections to split the information and make a reference to your objectId like:
var comments = new Schema({
subject: String,
body: String,
date: {
type: Date,
default: Date.now
},
pictures: [
{type: Schema.Types.ObjectId, ref: 'pictures'}
]
});
you'll need to separate each schema into it's own and delare a model for comments and images as well.
Either way both are valid if you ask me my personal preference is picking up embedded document approach.
EDIT:
this situation can be applied for N relationships between collections, I keep it simple for two relationships, but for you scenario could be like this:
var blogpost = new Schema({
title: String,
body: String,
date: {
type: Date,
default: Date.now
},
comments: [{
subject: String,
body: String,
date: {
type: Date,
default: Date.now
},
pictures:[{
picURL: String,
date: {
type: Date,
default: Date.now
}
}]
}]
});
referenced:
var blogpost = new Schema({
title: String,
body: String,
date: {
type: Date,
default: Date.now
},
comments:type: Schema.Types.ObjectId, ref: 'comments'}
});
hope that helps.

Resources