How to index mongoose-timestamp in elastic search - node.js

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 }
)

Related

Node mongoose fill createdBy and updatedBy column with userId in every Model save and update

In Node, Mongoose I am trying to achieve something like Laravel's created_by and updated_by columns, these 2 columns are automatically updated by the ORM in every INSERT and UPDATE operation to that particular table.
For example, below is the Material schema, here I want to store the createdBy and updatedBy column with userId whenever any user performs INSERT and UPDATE operations respectively in the materials collection.
I know this can be done while saving the records in particular controller method, but every time in every method I will have to add this and it becomes a pain, so I am looking for a solution where I can define something in the Model itself and it does the job just like the mongoose-delete package.
const mongoose = require('mongoose')
const mongoose_delete = require('mongoose-delete')
const materialSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
type: {
type: String,
required: true,
enum: ['hard', 'soft'],
},
image: {
type: String,
default: null
},
active: {
type: Boolean,
default: true
},
createdBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
default: null
},
updatedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
default: null
}
}, { timestamps: true })
materialSchema.plugin(mongoose_delete, { deletedAt : true, deletedBy : true, deletedByType: String })
const Material = mongoose.model("Material", materialSchema)
module.exports = Material

Mongoose find() returning empty Array of SchemaType

I have the following Schema type called Orders. I am using Arrays of SchemaTypes in some properties. When I save it to the database, it's saving everything fine. I can open the database and see all the data there.
But the problem happens in one property called "files", whenever I try to use find() or findOne() or findById(), this property always comes empty, even if I have data to show.
This is my Schemas:
const statusChildSchema = new Mongoose.Schema({
...
});
const shippingChildSchema = new Mongoose.Schema({
...
});
const fileChildSchema = new Mongoose.Schema({
path: { type: String, required: true, trim: true },
type: { type: String, required: true },
});
const ordersSchema = new Mongoose.Schema(
{
// Relationships
creator: {
type: Mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Users',
autopopulate: false,
},
template: {
type: Mongoose.Schema.Types.ObjectId,
ref: 'Templates',
},
// Common
status: { type: String, trim: true, default: 'new', required: true },
// Child schemas
status_updates: [statusChildSchema],
shipping: [shippingChildSchema],
files: [fileChildSchema],
// Date properties
timings: {
created_at: { type: Date, default: Date.now, required: true },
...
},
},
{ collection: 'Orders', toJSON: { virtuals: true } }
);
Both statusChildSchema and shippingChildSchema is working normally. The problem is only with fileChildSchema. They are very similar, so I don't know what to do. I have researched in Mongoose documents and nothing helpful have been found.
This is the part of my code:
const order = await OrdersModel.findOne({
_id: orderId,
creator: userId,
});
console.log(order.files); // always printing "[]" empty array
I fixed it by installing last version of Mongoose (Version 5.11.8) and restarting everything. Looks like a bug.

How to query and get documents from two collections on mongoose

I need to query documents from two collections together on mongoose.
I am familiar with SQL query and but not familiar with mongoDB.
I have two schema for Users, Messages like following.
Users
const UserSchema = new mongoose.Schema({
name: String,
email: {type: String, unique: true},
password: String,
avatar: {type: String, default: ""},
created_at: { type: Date, default: Date.now() }
});
module.exports = mongoose.model('User', UserSchema);
Messages
const MessageSchema = new mongoose.Schema({
message: { type: String, default: "" },
from: { type: String, default: "" },
to: { type: String: default: "" },
is_read: { type: Boolean, default: false },
channel: { type: String, default: ''},
created_at: { type: Date, required: true, default: Date.now }
});
module.exports = mongoose.model('Message', MessageSchema);
I need to get messages with "is_read" is "false".
I want to get "user name" and "avatar" together.
The "from" value of message should be matched with "_id" of User.
I think this post sums it up well: Mongoose - query to get data from multiple collections
Specifically the second upvoted answer mentions similarities between sql and mongodb, and goes on to explain how to link collections in mongoose queries.

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

Mongoose create multiple index and personalize quety to call with specific index

I would like to do many indexes over my model and when i am doing query use a specific index in that query
this is my model
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ThingSchema = new Schema({
word:{
type: 'ObjectId',
required:true
},
frecuency:{
type: String,
default:'enabled'
},
document:{
documentId:{
type: 'ObjectId'
},
quality:{
type: Number
}
},
location: {
type: [Number],
index: '2d'
},
createdAt: {
type: Date,
default: Date.now
},
updatedAt: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Thing', ThingSchema);
I would like to have these indexes:
index by word (is a string)
index by location (is geoindex)
index by word and location
Now when I am doing a query I would like to specify which index to use
Before your module.exports line:
ThingSchema.index({word: 1});
// all other indexes you want to add...
And when it's time to make a query, use hint() to specify which index to use:
Thing.find({...}).hint({word: 1});

Resources