sequelize return only first row ( through the include association) - postgresql

i am using sequelize include to associate the next three models
"moldsets" has many "molds" and "molds" has many "moldstatus"
// moldsets.model.js
const Sequelize = require("sequelize");
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get("sequelizeClient");
const moldsets = sequelizeClient.define(
"moldsets",
{
name: {
type: DataTypes.STRING,
allowNull: false,
},
vendor: {
type: DataTypes.STRING,
allowNull: false,
},
status: {
type: DataTypes.STRING,
allowNull: false,
},
number_of_blanks: {
type: DataTypes.INTEGER,
allowNull: false,
},
number_of_blows: {
type: DataTypes.INTEGER,
allowNull: false,
},
date_of_reception: {
type: DataTypes.DATE,
allowNull: false,
},
date_of_scrap: {
type: DataTypes.DATE,
allowNull: true,
},
},
{
hooks: {
beforeCount(options) {
options.raw = true;
},
},
}
);
// eslint-disable-next-line no-unused-vars
moldsets.associate = function (models) {
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/
const { molds } = models;
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/
moldsets.hasMany(molds, { foreignKey: "moldsetId" });
};
return moldsets;
};
//molds.model.js
const Sequelize = require("sequelize");
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get("sequelizeClient");
const molds = sequelizeClient.define(
"molds",
{
number: {
type: DataTypes.INTEGER,
allowNull: false,
},
kind: {
type: DataTypes.STRING,
allowNull: false,
},
moldsetId: {
type: DataTypes.INTEGER,
allowNull: false,
},
numberOfTotalGobs: {
type: DataTypes.INTEGER,
allowNull: false,
},
statusId: {
type: DataTypes.INTEGER,
allowNull: false,
},
note: {
type: DataTypes.STRING,
allowNull: false,
},
},
{
hooks: {
beforeCount(options) {
options.raw = true;
},
},
}
);
// eslint-disable-next-line no-unused-vars
molds.associate = function (models) {
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/
console.log(models);
const { moldsets, moldstatus } = models;
molds.belongsTo(moldsets);
molds.hasMany(moldstatus, { as: "status" });
};
return molds;
};
// moldstatus.model.js
const Sequelize = require("sequelize");
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get("sequelizeClient");
const moldstatus = sequelizeClient.define(
"moldstatus",
{
moldId: {
type: DataTypes.INTEGER,
allowNull: false,
},
status: {
type: DataTypes.STRING,
allowNull: false,
},
startdate: {
type: DataTypes.DATE,
allowNull: false,
},
enddate: {
type: DataTypes.DATE,
allowNull: true,
},
note: {
type: DataTypes.STRING,
allowNull: true,
},
lineId: {
type: DataTypes.INTEGER,
allowNull: false,
},
section: {
type: DataTypes.STRING,
allowNull: false,
},
defect: {
type: DataTypes.STRING,
allowNull: true,
},
numberOfGobs: {
type: DataTypes.INTEGER,
allowNull: false,
},
operatorId: {
type: DataTypes.INTEGER,
allowNull: false,
},
},
{
hooks: {
beforeCount(options) {
options.raw = true;
},
},
}
);
// eslint-disable-next-line no-unused-vars
moldstatus.associate = function (models) {
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/
const { molds } = models;
moldstatus.belongsTo(molds, { foreignKey: "statusId" });
};
return moldstatus;
};
but when i query the moldset ( i am using feathersjs so i am using it in the before find hook )
const related = async (context) => {
const sequelize = context.app.get("sequelizeClient");
const { molds, moldstatus } = sequelize.models;
context.params.sequelize = {
include: [
//{ all: true, nested: true },
{
model: molds,
attributes: ["number", "statusId"],
required: false,
order: [[molds, "number", "ASC"]],
include: [
{
model: moldstatus,
as: "status",
required: false,
attributes: ["status"],
//order: [[moldstatus, "created_at", "DESC"]],
},
],
raw: false,
},
],
raw: false,
};
return context;
};
module.exports = {
before: {
all: [
authenticate("jwt"),
(context) => {
related(context);
},
],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: [],
},
};
the result is i got all the moldsets with its molds but i got only the first mold status for the first mold only in each moldset ( the other molds got empty array )
i tried setting raw to true but i still got the status for the first mold in each moldset only ...
//result
[{
"id": 2,
"name": "fruity250ml1",
"vendor": "jacob",
"status": "mounted",
"number_of_blanks": 30,
"number_of_blows": 28,
"date_of_reception": "2021-04-26T13:22:00.000Z",
"date_of_scrap": null,
"createdAt": "2021-04-26T13:22:00.000Z",
"updatedAt": "2021-04-26T13:22:00.000Z",
"molds": [
{
"number": 1,
"statusId": 3,
"status": [
{
"status": "mounted"
}
]
},
{
"number": 2,
"statusId": 4,
"status": []
}
],
"mounted": null
},
{
"id": 1,
"name": "seles250ml1",
"vendor": "omco",
"status": "avalible",
"number_of_blanks": 30,
"number_of_blows": 28,
"date_of_reception": "2021-07-26T13:22:00.000Z",
"date_of_scrap": null,
"createdAt": "2021-07-26T13:22:00.000Z",
"updatedAt": "2021-07-26T13:22:00.000Z",
"molds": [
{
"number": 2,
"statusId": 2,
"status": []
},
{
"number": 3,
"statusId": 3,
"status": []
},
{
"number": 1,
"statusId": 3,
"status": [
{
"status": "avalible"
}
]
}
]
}
]
database :
molds:
moldstatus:
moldsets:

First of all, if you indicate a foreign key field in some association explicitly you should indicate it for the reversed association as well:
moldsets.hasMany(molds, { foreignKey: "moldsetId" });
...
molds.belongsTo(moldsets, { foreignKey: "moldsetId" });
molds.hasMany(moldstatus, { as: "status", foreignKey: "statusId" });
...
moldstatus.belongsTo(molds, { foreignKey: "statusId" });
And you indicated incorrect foreign key field for molds.hasMany(moldstatus so the above associations should be like this:
molds.hasMany(moldstatus, { as: "status", foreignKey: "moldId" });
...
moldstatus.belongsTo(molds, { foreignKey: "moldId" });

Related

How to find entire records using populated fields in mongoose

This are my schemas
var employeesSchema = new schema({
companyName: { type: String },
employeeName: { type: String },
employeeCode: { type: String, unique: true },
designation: { type: String },
department: { type: String },
officeLocation: { type: String },
workLocation: { type: String },
emailID: { type: String , unique: true},
managerName: { type: String },
managerEmail: { type: String },
countryCode: { type: String },
mobile: { type: String },
password: { type: String },
createdDate: { type: Date, default: new Date() }
})
var leaveRequests = new schema({
leaveRequestID: { type: String, unique: true },
employeeCode: { type: String, required: true },
requestedBy: { type: mongoose.Schema.Types.ObjectId, ref: "employees_master", required: true },
leaveType: { type: mongoose.Schema.Types.ObjectId, ref: "leavetypes", required: true },
startDate: { type: Date },
endDate: { type: Date },
remarks: { type: String },
documentUrl: { type: String },
status: { type: String, enum: ['pending', 'rejected', 'approved'], default: 'pending' },
statusUpdatedBy: { type: mongoose.Schema.Types.ObjectId, ref: "manager_or_lead_master" },
reason: { type: String },
isActive: { type: Boolean, default: true },
createdDate: { type: Date, default: new Date() },
});
Im trying to filter data with managerEmail: req.body.emailID
exports.getTeamLevelLeaveRequest = async (req, res) => {
try {
const getQuery = leaverequests.find({})
.populate('leaveType')
.populate('statusUpdatedBy')
.populate({
path: 'requestedBy',
match: {
managerEmail: req.body.emailID
}
})
.sort({ _id: -1 })
const resp = await getQuery;
const resAfterMap = resp.filter(u => u.requestedBy !== null)
responseHandler.successResponse(res, resAfterMap, "Leave Requests")
} catch (err) {
responseHandler.errorResponse(res, err, commonErrorMessage)
}
}
But Im receiving resp like
[{
"_id": "634e7459f78e446637a70ac6",
"leaveRequestID": "LR10",
"employeeCode": "MLI637",
"requestedBy": null,
"leaveType": {
"_id": "634d8d7ab69f5a80c4c98216",
"leaveType": "Compensatory Off",
"__v": 0,
"name": "Compensatory Off"
},
"startDate": "2022-10-18T18:30:00.000Z",
"endDate": "2022-10-18T18:30:00.000Z",
"remarks": "test",
"status": "pending",
"isActive": true,
"createdDate": "2022-10-18T08:27:42.042Z",
"__v": 0
},
{
"_id": "634e719c71313319a6da2432",
"leaveRequestID": "LR9",
"employeeCode": "MLI699",
"requestedBy": null,
"leaveType": {
"_id": "634d8d7ab69f5a80c4c98216",
"leaveType": "Compensatory Off",
"__v": 0,
"name": "Compensatory Off"
},
"startDate": "2022-10-18T18:30:00.000Z",
"endDate": "2022-10-18T18:30:00.000Z",
"remarks": "test",
"status": "pending",
"isActive": true,
"createdDate": "2022-10-18T08:25:04.220Z",
"__v": 0
},
{
"_id": "634e719c71313319a6da2432",
"leaveRequestID": "LR9",
"employeeCode": "MLI699",
"requestedBy": {
**populated data came ----**
},
"leaveType": {
"_id": "634d8d7ab69f5a80c4c98216",
"leaveType": "Compensatory Off",
"__v": 0,
"name": "Compensatory Off"
},
"startDate": "2022-10-18T18:30:00.000Z",
"endDate": "2022-10-18T18:30:00.000Z",
"remarks": "test",
"status": "pending",
"isActive": true,
"createdDate": "2022-10-18T08:25:04.220Z",
"__v": 0
},
]
I want to get data without filtering requestedBy is not equal to null
Im using filter method to do.
Is there any option to find filter data....

How to use $regex when searching for a value in a mongoose table that are referenced as foreign key?

I am trying to search the orders table and this is how the search controller looks like,
export const searchTable = async (req, res) => {
const { searchQuery } = req.query;
try {
const orders = await Order.find({
$or: [
{
paymentMethod: { $regex: searchQuery, $options: "i" },
},
{
delivery_status: { $regex: searchQuery, $options: "i" },
},
{
orderItems: {
$all: [
{
$elemMatch: {
name: { $regex: searchQuery, $options: "i" },
},
},
],
},
},
],
});
res.status(200).json({ data: orders });
} catch (error) {
res.status(404).json({ message: error });
console.log(error);
}
};
This is the data structure of the table I'm searching from;
orderItems: [
{
orderId: {
type: mongoose.Schema.Types.ObjectId,
ref: "PostListing",
required: false,
},
name: { type: String, required: true },
qty: { type: Number, required: true },
price: { type: Number, required: true },
imageUrl: { type: String, required: false },
delivery_status: {
type: String,
enum: ["DELIVERED", "REJECTED"],
required: false,
},
},
],
How can use the searchQuery to get the orderId which is a ref/foreign key from PostListing? Thank you!

sequelize eager loading returns null for associated table record. Why?

I want to retrieve data from an associated table but the returned value is null.
This is the association
static associate(models) {
appointment.hasOne(models.member, {
foreignKey: "id",
sourceKey: "member_id",
constraints: false,
});
appointment.hasOne(models.system_data, {
foreignKey: "id",
sourceKey: "facility_id",
constraints: false,
as: "system_data",
});
}
Members association is returned correctly but when I try to get system_data I get null even if it is present in database.
Here I try to get:
const getRelatedTableRecords = () =>
include?.split(",").map((table) => {
if (schemaName === "appointment" && table === "system_data") {
return { model: db[table], as: "system_data", required: false };
}
return { model: db[table] };
});
I don't understand why I can't get system_data. What might be the reasons?? Do you have any suggestions?
Member object
class Member extends Model {
static associate(models) {
// define association here
Member.hasMany(models.card, {
foreignKey: "card_id",
sourceKey: "card_id",
});
Member.hasMany(models.club, {
foreignKey: "id",
sourceKey: "club",
constraints: false,
});
Member.hasMany(models.schedule, {
foreignKey: "id",
sourceKey: "schedule",
constraints: false,
});
Member.hasMany(models.trainer, {
foreignKey: "id",
sourceKey: "trainer",
constraints: false,
});
Member.hasMany(models.file, {
foreignKey: "owner_id",
sourceKey: "id",
constraints: false,
});
Member.hasOne(models.facilities, {
foreignKey: "id",
sourceKey: "facility_id",
constraints: false,
});
}
}
Member.init(
{
first_name: {
type: DataTypes.STRING,
allowNull: false,
},
last_name: {
type: DataTypes.STRING,
allowNull: false,
},
tc_no: {
type: DataTypes.BIGINT,
allowNull: false,
unique: true,
},
password: {
type: DataTypes.STRING,
},
card_id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
unique: true,
allowNull: false,
},
registered: {
type: DataTypes.BOOLEAN,
defaultValue: false,
allowNull: false,
},
schedule: {
type: DataTypes.INTEGER,
references: {
model: "schedules",
key: "id",
},
onDelete: "CASCADE",
},
club: {
type: DataTypes.INTEGER,
references: {
model: "clubs",
key: "id",
},
onDelete: "CASCADE",
allowNull: true,
},
trainer: {
allowNull: true,
type: DataTypes.INTEGER,
references: {
model: "trainers",
key: "id",
},
onDelete: "CASCADE",
},
birthplace: {
type: DataTypes.STRING,
allowNull: true,
},
birthdate: { type: DataTypes.DATE, allowNull: true },
father_name: { type: DataTypes.STRING, allowNull: true },
mother_name: { type: DataTypes.STRING, allowNull: true },
gender: { type: DataTypes.STRING, allowNull: true },
profession: { type: DataTypes.STRING, allowNull: true },
address: { type: DataTypes.STRING, allowNull: true },
phone_number: { type: DataTypes.STRING, allowNull: true },
hes_code: { type: DataTypes.STRING, allowNull: true },
blood_type: { type: DataTypes.STRING, allowNull: true },
nationality: { type: DataTypes.STRING, allowNull: true },
profile_photo: {
type: DataTypes.STRING,
allowNull: true,
},
file: {
type: DataTypes.STRING,
allowNull: true,
},
session_ids: { type: DataTypes.ARRAY(DataTypes.STRING) },
facility_id: { type: DataTypes.INTEGER },
following: { type: DataTypes.ARRAY(DataTypes.INTEGER) },
creator: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
updater: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
},
{
sequelize,
modelName: "member",
hooks: {
afterCreate: (member, options) => {
sequelize.models.card.create({
card_id: member.card_id,
credits: 0,
creator: member.creator,
updater: member.updater,
});
},
beforeUpdate: (member, options) => {
const changed = member.changed();
if (changed?.includes("card")) {
sequelize.models.member.update(
{ trainer: null },
{ where: { id: member.dataValues.id } }
);
}
if (changed?.includes("trainer")) {
sequelize.models.member.update(
{ club: null },
{ where: { id: member.dataValues.id } }
);
}
},
},
}
);
system_data obj
class System_data extends Model {
static associate(models) {
// define association here
System_data.hasOne(models.facilities, {
foreignKey: "id",
sourceKey: "facility_id",
constraints: false,
});
}
}
System_data.init(
{
app_id: { type: DataTypes.STRING },
province: DataTypes.STRING,
district: DataTypes.STRING,
address: DataTypes.TEXT,
phone: DataTypes.STRING,
reset_credits: { type: DataTypes.BOOLEAN, defaultValue: false },
asset_path: {
type: DataTypes.STRING,
},
card_price: {
type: DataTypes.DECIMAL,
allowNull: false,
defaultValue: 0.0,
},
ticket_price: {
type: DataTypes.DECIMAL,
allowNull: false,
defaultValue: 0.0,
},
facility_id: { type: DataTypes.INTEGER },
working_hours: { type: DataTypes.STRING },
capacity: DataTypes.BIGINT,
season_based: { type: DataTypes.BOOLEAN, defaultValue: false },
appointment_based: { type: DataTypes.BOOLEAN, defaultValue: false },
seasons: {
type: DataTypes.ARRAY(DataTypes.STRING),
},
season_capacity: {
type: DataTypes.INTEGER,
},
},
{
sequelize,
modelName: "system_data",
}
);
As I can see system_data has facility_id as a foreign key to appointment so for appointment it should be like this:
appointment.hasOne(models.system_data, {
foreignKey: "facility_id",
constraints: false,
as: "system_data",
});
In both associations of the pair hasOne/belongsTo you should indicate the same foreignKey option with the same value that should point to a foreign key field on N side table in 1:N relationship.
There is no need to indicate sourceKey as long as you use a primary key field of the 1 side table in 1:N relationship.

How to create this tsvector generated always as column with sequelize?

I see that sequelize has DataTypes.TSVECTOR for postgres dialect.
I have a column whose definition in raw SQL is as follows
tsvector GENERATED ALWAYS AS (((
setweight(to_tsvector('english'::regconfig, (COALESCE(title, ''::character varying))::text), 'A'::"char") ||
setweight(to_tsvector('english'::regconfig, COALESCE(summary, ''::text)), 'B'::"char")) ||
setweight(to_tsvector('english'::regconfig, (COALESCE(content, ''::character varying))::text), 'C'::"char")))
STORED
How can I define this in my sequelize model
const FeedItem = sequelize.define(
'FeedItem', {
feedItemId: {
type: DataTypes.UUID,
primaryKey: true,
allowNull: false,
defaultValue: DataTypes.UUIDV4,
},
pubdate: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: sequelize.literal('CURRENT_TIMESTAMP'),
validate: {
isDate: true,
},
},
link: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [0, 2047],
},
},
guid: {
type: DataTypes.STRING,
validate: {
len: [0, 2047],
},
},
title: {
type: DataTypes.TEXT,
allowNull: false,
validate: {
len: [0, 65535],
},
},
summary: {
type: DataTypes.TEXT,
validate: {
len: [0, 65535],
},
},
content: {
type: DataTypes.TEXT,
validate: {
len: [0, 1048575],
},
},
author: {
type: DataTypes.STRING,
validate: {
len: [0, 63],
},
},
tags: {
type: DataTypes.ARRAY(DataTypes.STRING),
defaultValue: [],
},
// How to do that generated always part here???
searchable: {
type: DataTypes.TSVECTOR
},
}, {
timestamps: false,
underscored: true,
indexes: [
{
name: 'idx_feed_items_searchable',
fields: ['searchable'],
using: 'gin',
},
],
}
);
The model needs to be modified as follows to get this working
const FeedItem = sequelize.define(
'FeedItem',
{
feedItemId: {
type: DataTypes.UUID,
primaryKey: true,
allowNull: false,
defaultValue: DataTypes.UUIDV4,
},
pubdate: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: sequelize.literal('CURRENT_TIMESTAMP'),
validate: {
isDate: true,
},
},
link: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [0, 2047],
},
},
guid: {
type: DataTypes.STRING,
validate: {
len: [0, 2047],
},
},
title: {
type: DataTypes.TEXT,
allowNull: false,
validate: {
len: [0, 65535],
},
},
summary: {
type: DataTypes.TEXT,
validate: {
len: [0, 65535],
},
},
content: {
type: DataTypes.TEXT,
validate: {
len: [0, 1048575],
},
},
author: {
type: DataTypes.STRING,
validate: {
len: [0, 63],
},
},
tags: {
type: DataTypes.ARRAY(DataTypes.STRING),
defaultValue: [],
},
// https://stackoverflow.com/questions/67051281/use-postgres-generated-columns-in-sequelize-model
searchable: {
type: `tsvector GENERATED ALWAYS AS (((setweight(to_tsvector('english'::regconfig, (COALESCE(title, ''::character varying))::text), 'A'::"char") || setweight(to_tsvector('english'::regconfig, COALESCE(summary, ''::text)), 'B'::"char")) || setweight(to_tsvector('english'::regconfig, (COALESCE(content, ''::character varying))::text), 'C'::"char"))) STORED`,
set() {
throw new Error('generatedValue is read-only');
},
},
},
{
timestamps: false,
underscored: true,
indexes: [
{
name: 'idx_feed_items_pubdate_feed_item_id_desc',
fields: [
{ attribute: 'pubdate', order: 'DESC' },
{ attribute: 'feed_item_id', order: 'DESC' },
],
},
{
name: 'idx_feed_items_tags',
fields: ['tags'],
using: 'gin',
},
{
name: 'idx_feed_items_searchable',
fields: ['searchable'],
using: 'gin',
},
],
}
);
Does not work with sequelize.sync({alter: true}) you have to force:true or sequelize migrations

mongoose populate query doesn't show the desired results

I'm new to MongoDB and Mongoose and I'm having some problems with it, to be more specific I've problems with populate, problem displayed below.
My Schema:
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
/* ------------------------------------- Field config ---------------------------------------- */
const UsersSchema = new Schema({
name: {
type: String,
required: true,
min: 3,
set: str => str.replace(/\b\w/g, l => l.toUpperCase())
},
lastname: {
type: String,
required: true,
min: 3,
set: str => str.replace(/\b\w/g, l => l.toUpperCase())
},
email: {
type: String,
required: true,
unique: true,
validade: {
validator: str => regExp.test(str)
}
},
password: {
type: String,
required: true,
min: 8
},
fcm:{
type: String,
required: true
},
birthDate: {
type: Date,
required: true,
get: convertToBR
},
gender: {
type: String,
enum: ['M', 'F'],
required: true
},
profileImage: {
type: String,
required: false,
get: alterUri
},
aboutMe: {
type: String,
max: 500
},
enabled: {
type: Boolean,
required: true,
default: true
},
createdAt: {
type: Date,
required: true,
default: new Date()
},
token: {
type: String,
required: true,
index: true
},
locations: {
type: [mongoose.Schema.Types.ObjectId],
require: false,
ref: 'Location'
},
lastVisitants: {
type: [{
user: mongoose.Schema.Types.ObjectId,
createAt: {
type: Date,
required: true,
default: new Date()
}
}],
required: false,
ref: 'Users'
}
}, {
toObject: {
virtuals: true,
getters: true,
setters: true
},
toJSON: {
virtuals: true,
getters: true,
setters: true
}
});
//Code bellow removed for make to easy know
Generated doc inside MongoDB:
{
"_id": "589288de533c9555163cf263",
"email": "luiz#sene.com",
"password": "CQziXoB6XrBFBTWe5s/kFsIGYqbtDPBBKQgADUZF9co=",
"name": "luiz Fernando",
"lastname": "Sene",
"birthDate": "1988-08-11T00:00:00.000Z",
"gender": "M",
"fcm": "34567890987654345678",
"token": "58979c08b048917ed8b434ac",
"createdAt": "2017-02-02T01:17:38.168Z",
"enabled": true,
"__v": 0,
"aboutMe": "algo sobre mim aqui mudar",
"locations": [
"5893e2e0c8a01b4ed21c8c39",
"5893e305c8a01b4ed21c8c3a",
"5893e32ac8a01b4ed21c8c3b",
"5893e34dc8a01b4ed21c8c3c",
"5893e92838bd205ba42c2c8a",
"5893ea888628c45d2bc6683a"
],
"profileImage": "images/589288de533c9555163cf263/1486330852976.png",
"lastVisitants": [
{
"createAt": "2017-02-05T19:23:17.697Z",
"_id": "58977ba99fc2b7485dbdbf26",
"user": "589778e22a9dd5449e4f92df"
}
]
}
My problem occurs when I try populate locations and lastVisitants.
My consult is below:
UsersSchema.findOne({_id: data.data.id}, {lastVisitants: true, locations: true})
.populate({
path: 'locations',
model: 'Location',
select: 'description',
options: {
limit: 1,
sort: {
createdAt: -1
}
}
})
.populate({
path: 'lastVisitants.user',
model: 'Users',
select: '_id lastVisitants',
options: {
limit: 5
//TODO: Add sort by createdAt
}
})
.exec((err, result) => {
if (err) {
Utils.callback(err, null, res);
return;
}
Utils.callback(null, result, res);
});
Result of my consult:
{
"_id": "589288de533c9555163cf263",
"lastVisitants": [
{
"_id": "58977c1c9fc2b7485dbdbf27",
"user": {
"_id": "589778e22a9dd5449e4f92df",
"lastVisitants": [
{
"_id": "58977c1c9fc2b7485dbdbf27",
"user": "589288de533c9555163cf263",
"createAt": "2017-02-05T19:23:17.697Z"
}
],
"profileImage": "http://192.168.0.19:3000/undefined",
"birthDate": {
"en": "NaN-NaN-NaN",
"br": "NaN/NaN/NaN"
},
"fullname": "undefined undefined",
"age": null,
"id": "589778e22a9dd5449e4f92df"
},
"createAt": "2017-02-05T19:23:17.697Z"
}
],
"profileImage": "http://192.168.0.19:3000/undefined",
"birthDate": {
"en": "NaN-NaN-NaN",
"br": "NaN/NaN/NaN"
},
"fullname": "undefined undefined",
"age": null,
"id": "589288de533c9555163cf263"
}
Result expected:
{
"_id": "589288de533c9555163cf263",
"locations":[
{
"_id": "5893ea888628c45d2bc6683a",
"description": "Cruzeiro - SP, Brasil"
}
]
"lastVisitants": [
{
_id: ""
user: {
"id": "58977ba99fc2b7485dbdbf26",
"fullname": "Fábio Pereira",
"profileImage": "http://192.168.0.19:3000/images/589288de533c9555163cf263/1486319528451.jpeg",
"gender": "M",
// more fields ...
},
createdAt: ""
}
]
}
My question is how can I make this query bring what I really desire?