I use a Model that, simplifying a lot, has some custom functions such as:
let MySchema = new mongoose.Schema({
email: {type: String, required: true, unique: true},
firstName: {type: String},
lastName: {type: String},
status: {type: String}
})
// Model custom functions
MySchema = {
login(email, callback) {...},
logout(email, callback) {...},
...
}
// This works
MySchema.findOne({email: userId}).then(user => user.loging())
// This also works
let user = await MySchema.findOne({email: userId})
user.logout()
... apply AppUsers as mongoose model of such Schema
// This works
let users = await AppUser.aggregate([
{
"$lookup": {
"from": "stg_appusers",
"localField": "email",
"foreignField": "email",
"as": "stg"
}
},
{
"$match": {
"stg.email": {
"$exists": false
}
}
},
{
"$match": {
status: "expired"
}
}
]).exec()
// At this point the aggregate() returns correctly what
// I need from the query (difference but two collections)
// as array, but each element of the array is not a Model
// for which I can invoke my Model custom functions
users.forEach(user => {
user.logout() // ⚠️ This doesn't work: TypeError: user.lgout is not a function
})
// I am using following as workaround...
users.forEach(user => {
AppUsers.findOne({email: user.email}).then(userFetched => userFetched.logout()) // This works, but...
})
Overall, the code is working by using AppUser.findOne({email: user.email}).then(userFetched => userFetched.logout())
but clearly is not performant: after the aggregate()
I am not able to use the logout()
function, so I have to call a find()
for each user returned from the aggregate()
.
Calling findOne()
for each user found by the aggregate()
would be fine, but the two Collections have similarly more than 1.000.000 users and the findOne() takes too time.
Why I can't call users := user.logout()
where users is the result of the aggregate()
?
Update from comment:
[
{
_id: 6040fd38191f66368dfe4ca0,
status: 'active',
email: 'some.one@coolcompany.com',
firstName: 'some',
lastName: 'one',
... many other fields, such as in the findOne()
}
]