const mongoose = require('mongoose'); const Schema = mongoose.Schema; mongoose.Promise = global.Promise; mongoose.level = "F"; const { ObjectID } = require('mongodb'); // Resolving error Unknown modifier: $pushAll mongoose.plugin(schema => { schema.options.usePushEach = true }); const sendmsgSchema = new Schema({ idapp: { type: String, }, origin: { userId: { type: String }, page: { type: String }, event_id: { type: String } }, dest: { idapp: { type: String, }, username: { type: String }, }, message: { type: String, }, datemsg: { type: Date, }, read: { type: Boolean, default: false }, deleted: { type: Boolean, default: false }, }); sendmsgSchema.statics.findAllByUserIdAndIdApp = function (userId, username, idapp) { const SendMsg = this; return SendMsg.find({ $and: [ { $or: [ { 'origin.userId': userId }, { 'dest.username': username }] }, { idapp } ] }, (err, arrmsg) => { return arrmsg }); }; sendmsgSchema.statics.findLastGroupByUserIdAndIdApp = function (userId, username, idapp) { const SendMsg = this; return SendMsg.aggregate([ { $match: { $or: [{ 'origin.userId': userId }, { 'dest.username': username }, { idapp }], $and: [{ idapp }] } }, { $group: { _id: "$dest.username", message: { $last: "$message" }, datemsg: { $last: "$datemsg" }, dest: { $last: "$dest" }, origin: { $last: "$origin" }, read: { $last: "$read" } } }, { $sort: { datemsg: -1 } }, ]) .then((arrmsg) => { console.table(arrmsg); return arrmsg }).catch((err) => { console.error(err); }); }; const SendMsg = mongoose.model('SendMsg', sendmsgSchema); module.exports = { SendMsg };