Avj conditional schema validation based on property value - node.js

I'm trying to validate the bellow json with ajv but i'm running into problems with validating the inputs options because the validation change based on the inputs type.
I found this post which was very helpful but im still a bit stuck
My json:
{
"name": "test Template",
"canvasSize": {"width": 2480, "height": 3508},
"inputs": [
{
"hidden": true,
"name": "Background",
"type": "background",
"position": {"x": "0", "y": 0},
"value": "http://localhost:3000/Featurecompactv2.jpg",
"options": {}
}, {
"name": "Title Line",
"group": "title",
"type": "text",
"position": {"x": "center", "y": 1400},
"options": {
"fontSize": 240,
"font": "Arial Black",
"color": "black",
"textAlign": "center",
"textBaseline": "alphabetic",
"direction": "inherit"
}
},
{
"name": "Image",
"type": "image",
"position": {"x": "center", "y": 2200},
"options": {
"maxWidth": 1000,
"maxHeight": 1000
}
},
{
"name": "Barcode",
"type": "barcode",
"position": {"x": 2100, "y": 2800},
"options": {
"width": 4,
"height": 35,
"fontSize": 35
}
}
]
}
My schema so far:
const positionSchema = {
type: "object",
properties: {
x: { oneOf: [{ type: "number" }, { enum: ["center"] }] },
y: { oneOf: [{ type: "number" }, { enum: ["center"] }] },
},
};
const textOptionsSchema = {
type: "object",
properties: {
fontSize: { type: "number" },
font: { type: "string" },
color: { type: "string" },
textAlign: { type: "string" },
textBaseline: { type: "string" },
direction: { type: "string" },
prefix: { type: "string" },
disabled: { type: "boolean" },
},
additionalProperties: false,
};
const barcodeOptionsSchema = {
type: "object",
properties: {
format: {
type: "string",
enum: [
"code128",
"code128A",
"code128B",
"code128C",
"EAN2",
"EAN5",
"EAN8",
"EAN13",
"UPC",
"CODE39",
"ITF14",
"MSI",
"MSI10",
"MSI11",
"MSI1010",
"MSI1110",
"pharmacode",
"codabar",
],
},
width: { type: "number" },
height: { type: "number" },
fontSize: { type: "number" },
margin: { type: "number" },
background: { type: "string" },
displayValue: { type: "boolean" },
disabled: { type: "boolean" },
},
additionalProperties: false,
};
const imageOptionsSchema = {
type: "object",
properties: {
maxWidth: { type: "number" },
maxHeight: { type: "number" },
width: { type: "number" },
height: { type: "number" },
backgroundRemoval: { type: "boolean" },
backgroundRemovalThreshold: { type: "number" },
disabled: { type: "boolean" },
},
additionalProperties: false,
};
const backgroundOptionsSchema = {
type: "object",
properties: {
disabled: { type: "boolean" },
},
additionalProperties: false,
};
const itemSchema = {
type: "object",
properties: {
hidden: { type: "boolean" },
name: { type: "string" },
position: positionSchema,
value: { type: "string" },
placeholder: { type: "string" },
group: { type: "string" },
type: {const: "background"},
}
required: ["name", "type", "position", "options"],
additionalProperties: false,
};
const schema = {
type: "object",
properties: {
name: { type: "string" },
canvasSize: {
type: "object",
properties: {
width: { type: "number" },
height: { type: "number" },
},
},
inputs: {
type: "array",
items: itemSchema
},
},
required: ["name", "canvasSize", "inputs"],
additionalProperties: false,
};
I think i need something like this but not sure how to add it to the schema:
oneOf: [
{
properties: {
type: {const: "text"},
options: textOptionsSchema
}
},
{
properties: {
type: {const: "background"},
options: backgroundOptionsSchema
}
}
],
Or if then thing but i couldn't get either to work

Related

MongoDB - Aggregation Query want to match 2 _id

I want to keep only that data in counts which will be matched with it's parent id for each individual document.
Student Schema
const StudentSchema = new mongoose.Schema(
{
name: {
type: String,
required: [true, "Please Provide Name"],
maxlength: 100,
minlength: 2,
},
email: {
type: String,
required: [true, "Please Provide Email"],
match: [
/^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
"Please Provide a Valid Email",
],
unique: true,
},
number: {
type: String,
required: [true, "Please Provide Number"],
match: [
/^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$/,
"Please Provide a Valid Number",
],
unique: true,
},
rollNumber: {
type: Number,
required: [true, "Please Provide Roll Number"],
maxlength: 5,
},
departmentID: {
type: mongoose.Types.ObjectId,
ref: "Department",
required: [true, "Please Provide departmentID"],
},
classID: {
type: mongoose.Types.ObjectId,
ref: "Class",
required: [true, "Please Provide classID"],
},
position: {
type: String,
required: [true, "Please Provide Position"],
enum: ["Student"],
default: "Student",
},
password: {
type: String,
required: [true, "Please Provide Password"],
minlength: 6,
},
},
{ timestamps: true }
);
Attendance Schema
const AttendanceSchema = new Schema(
{
date: {
type: String,
required: [true, "Please Provide Date"],
maxlength: 15,
minlength: 5,
},
subjectID: {
type: mongoose.Types.ObjectId,
ref: "Subject",
required: [true, "Please Provide Subject"],
},
studentID: {
type: mongoose.Types.ObjectId,
ref: "Student",
required: [true, "Please Provide Student"],
},
teacherID: {
type: mongoose.Types.ObjectId,
ref: "Faculty",
required: [true, "Please Provide Teacher"],
},
classID: {
type: mongoose.Types.ObjectId,
ref: "Class",
required: [true, "Please Provide Class"],
},
departmentID: {
type: mongoose.Types.ObjectId,
ref: "Department",
required: [true, "Please Provide Department"],
},
},
{ timestamps: true }
);
My Query
const data = await StudentSchema.aggregate([
{ $match: { classID: mongoose.Types.ObjectId(`${req.params.id}`) } },
{
$lookup: {
from: "attendances",
pipeline: [
{
$match: {
subjectID: mongoose.Types.ObjectId(`${req.params.Sid}`),
},
},
{ $group: { _id: "$studentID", count: { $sum: 1 } } },
],
as: "counts",
},
},
]);
This is the data I'm getting from this query:
{
"data": [
{
"_id": "63677d2960fa65e95aef5e95",
"name": "Lavannya Urkande",
"email": "lavannya#gmail.com",
"number": "9130354519",
"rollNumber": 201,
"departmentID": "6365531fdc02a121ffeed944",
"classID": "636554e8dc02a121ffeed982",
"position": "Student",
"password": "$2a$10$mqysVgtIGrYbvMGtHE2vbu0z5g05BlwJizcc.CfWMld78VPrnvcrO",
"createdAt": "2022-11-06T09:23:53.803Z",
"updatedAt": "2022-11-06T09:23:53.803Z",
"__v": 0,
"counts": [
{
"_id": "6367819d60fa65e95aef5ea7",
"count": 2,
},
{
"_id": "63677d2960fa65e95aef5e95",
"count": 3,
}
]
},
{
"_id": "6367819d60fa65e95aef5ea7",
"name": "Sohan Shinde",
"email": "soham#gmail.com",
"number": "9130354510",
"rollNumber": 202,
"departmentID": "6365531fdc02a121ffeed944",
"classID": "636554e8dc02a121ffeed982",
"position": "Student",
"password": "$2a$10$DuXjtayCPgGwkNnpog5IYeEEkY56igtlA/m6vobT44wmlSLcXp1eK",
"createdAt": "2022-11-06T09:42:53.861Z",
"updatedAt": "2022-11-06T09:42:53.861Z",
"__v": 0,
"counts": [
{
"_id": "6367819d60fa65e95aef5ea7",
"count": 2,
},
{
"_id": "63677d2960fa65e95aef5e95",
"count": 3,
}
]
}
]
}
But I want this type of data from my query(counts)
The only data which matched with it's parent _id. Notice the _id and counts._id then you can understand my request.
{
"data": [
{
"_id": "63677d2960fa65e95aef5e95",
"name": "Lavannya Urkande",
"email": "lavannya#gmail.com",
"number": "9130354519",
"rollNumber": 201,
"departmentID": "6365531fdc02a121ffeed944",
"classID": "636554e8dc02a121ffeed982",
"position": "Student",
"password": "$2a$10$mqysVgtIGrYbvMGtHE2vbu0z5g05BlwJizcc.CfWMld78VPrnvcrO",
"createdAt": "2022-11-06T09:23:53.803Z",
"updatedAt": "2022-11-06T09:23:53.803Z",
"__v": 0,
"counts": [
{
"_id": "63677d2960fa65e95aef5e95",
"count": 3,
}
]
},
{
"_id": "6367819d60fa65e95aef5ea7",
"name": "Sohan Shinde",
"email": "soham#gmail.com",
"number": "9130354510",
"rollNumber": 202,
"departmentID": "6365531fdc02a121ffeed944",
"classID": "636554e8dc02a121ffeed982",
"position": "Student",
"password": "$2a$10$DuXjtayCPgGwkNnpog5IYeEEkY56igtlA/m6vobT44wmlSLcXp1eK",
"createdAt": "2022-11-06T09:42:53.861Z",
"updatedAt": "2022-11-06T09:42:53.861Z",
"__v": 0,
"counts": [
{
"_id": "6367819d60fa65e95aef5ea7",
"count": 2,
}
]
}
]
}
You can use filter method in your $project
const data = await StudentSchema.aggregate([
{ $match: { classID: mongoose.Types.ObjectId(`${req.params.id}`) } },
{
$lookup: {
from: "attendances",
pipeline: [
{
$match: {
subjectID: mongoose.Types.ObjectId(`${req.params.Sid}`),
},
},
{ $group: { _id: "$studentID", count: { $sum: 1 } } },
],
as: "counts",
},
},
{
$project: {
classID: 1,
departmentID: 1,
email: 1,
name: 1,
number: 1,
position: 1,
rollNumber: 1,
counts: {
$filter: {
input: "$counts",
cond: {
$eq: ["$$this._id", "$_id"],
},
},
},
},
},
]);

How to add field in array with aggregate mongoose from another array coming from previous stage

I have two mongoose schema one for keywords :
const keywordSchema = new Schema<keywordI>(
{
sentence: { type: String, required: true },
example: { type: String, required: true },
translate: { type: String, required: true },
imageUrl: { type: String, required: true },
audioUrl: { type: String, required: true },
deletedAt: { type: Date, select: false },
},
{ timestamps: true }
);
and one for keywordsUser :
const keywordUserSchema = new Schema<keywordUserI>(
{
keywordId: {
type: mongoose.Types.ObjectId,
ref: "Keyword",
required: true,
},
userId: {
type: mongoose.Types.ObjectId,
ref: "User",
required: true,
},
isBookMarked: { type: Boolean, default: false },
correctAnswer: { type: Number, default: 0 },
wrongAnswer: { type: Number, default: 0 },
},
{ timestamps: true }
);
I want to get keywords by user grouped by type which I calculate from wrongAnswer and correctAnswer
I try to do this using aggregate
return KeyWordUser.aggregate([
{
$match: { userId },
},
{
$addFields: {
type: {
$function: {
body: getType,
args: ["$correctAnswer", "$wrongAnswer"],
lang: "js",
},
},
},
},
{
$group: {
_id: "$type",
words: {
$push: "$keywordId",
},
isBookMarked: {
$push: { isBookMarked: "$isBookMarked", keywordId: "$keywordId" },
},
},
},
{
$lookup: {
localField: "words",
from: "keywords",
foreignField: "_id",
as: "props",
},
},
{
$addFields: { type: "$_id" },
},
{
$project: {
_id: 0,
words: 0,
},
},
]);
I have this result from aggregate
returned data from. postman
I want to add new aggregate stage to get this result
previous result
[
{
"isBookMarked": [
{
"keywordId": "62e2a0ad3113b8234511cd72"
},
{
"isBookMarked": false,
"keywordId": "62e2a0ba3113b8234511cd74"
}
],
"props": [
{
"_id": "62e2a0ad3113b8234511cd72",
"sentence": "hello",
"example": "Hello , what's your name",
"translate": "مرحبا ما اسمك",
"imageUrl": "src/img/keywords/keyword-A7H_M-1659019437698.png",
"audioUrl": "src/audio/keywords/keyword-YyhUp-1659019437700.mpeg",
"createdAt": "2022-07-28T14:43:57.708Z",
"updatedAt": "2022-07-28T14:43:57.708Z",
"__v": 0
},
{
"_id": "62e2a0ba3113b8234511cd74",
"sentence": "hello 2 ",
"example": "Hello , what's your name 2 ",
"translate": "مرحبا ما اسمك 2",
"imageUrl": "src/img/keywords/keyword-2JO7D-1659019450396.png",
"audioUrl": "src/audio/keywords/keyword-kt5Tc-1659019450397.mpeg",
"createdAt": "2022-07-28T14:44:10.400Z",
"updatedAt": "2022-07-28T14:44:10.400Z",
"__v": 0
}
],
"type": "strong"
}
]
and i want this result :
[
{
"props": [
{
"_id": "62e2a0ad3113b8234511cd72",
"sentence": "hello",
"example": "Hello , what's your name",
"translate": "مرحبا ما اسمك",
"imageUrl": "src/img/keywords/keyword-A7H_M-1659019437698.png",
"audioUrl": "src/audio/keywords/keyword-YyhUp-1659019437700.mpeg",
"createdAt": "2022-07-28T14:43:57.708Z",
"updatedAt": "2022-07-28T14:43:57.708Z",
"__v": 0
},
{
"_id": "62e2a0ba3113b8234511cd74",
"isBookMarked" : false
"sentence": "hello 2 ",
"example": "Hello , what's your name 2 ",
"translate": "مرحبا ما اسمك 2",
"imageUrl": "src/img/keywords/keyword-2JO7D-1659019450396.png",
"audioUrl": "src/audio/keywords/keyword-kt5Tc-1659019450397.mpeg",
"createdAt": "2022-07-28T14:44:10.400Z",
"updatedAt": "2022-07-28T14:44:10.400Z",
"__v": 0
}
],
"type": "strong"
}
]
You can just populate with the keywordId not with aggregate

I Want to remove the video if free_preview: false in nodejs express

if its free_preview is true means, the video data must preview to all and when the free_preview is false means its not might expose the video data.
But in this scenario if free_preview is false then also the video data is expose.
i want to make this to preview the videos wheather the free_preview is true otherwise the videos doesn't expose.
how can i solve this?
-----------------API CODE--------------------
export const courses = async (req, res) => {
const all = await Course.find({ published: true})
.populate("instructor", "_id name")
.exec();
res.json(all)
};
import { json } from "express";
import mongoose from "mongoose";
const { ObjectId } = mongoose.Schema;
const lessonSchema = new mongoose.Schema(
{
title: {
type: String,
trim: true,
minlength: 3,
maxlength: 320,
required: true,
},
slug: {
type: String,
lowercase: true,
},
content: {
type: String,
minlength: 200,
},
video: {},
time:{
type: Number,
required: true,
trim: true,
min: 1,
max: 5
},
free_preview: {
type: Boolean,
default: false,
},
},
{ timestamps: true }
);
const courseSchema = new mongoose.Schema(
{
name: {
type: String,
trim: true,
minlength: 3,
maxlength: 320,
required: true,
},
slug: {
type: String,
lowercase: true,
},
description: {
type: {},
minlength: 200,
required: true,
},
price: {
type: Number,
default: 500,
},
image: {},
category: String,
published: {
type: Boolean,
default: false,
},
paid: {
type: Boolean,
default: true,
},
instructor: {
type: ObjectId,
ref: "User",
required: true,
},
Category:{
type : String,
trim: true,
min: 4,
max: 200
},
lessons: [lessonSchema],
},
{ timestamps: true }
);
export default mongoose.model("Course", courseSchema);
----------------------------api response ----------------------------------
[
{
"price": 400,
"published": true,
"paid": true,
"_id": "61d73468f0ef1c2df856d580",
"slug": "nmap-for-ethical-hacking",
"instructor": {
"_id": "61d73336f0ef1c2df856d57f",
"name": "lenin royal"
},
"name": "Nmap for ethical hacking",
"description": "sfdsfdf",
"lessons": [
{
"free_preview": false,
"_id": "61d73721da89b03378321bc3",
"title": "intro",
"content": "sdfdfdff",
"video": {
"Location": "https://berrys01.s3.ap-south-1.amazonaws.com/_k8b_Khyz9GgTZkomm7WS.mp4",
"Bucket": "berrys01",
"Key": "_k8b_Khyz9GgTZkomm7WS.mp4",
"ETag": "\"00bf0fea24f997ac205c16de2ca3f7fa-2\""
},
"slug": "intro",
"updatedAt": "2022-01-06T18:38:25.674Z",
"createdAt": "2022-01-06T18:38:25.674Z"
},
{
"free_preview": true,
"_id": "61d737b8da89b03378321bc4",
"title": "hgdsfhgsdf",
"content": "dfsdfdf",
"video": {
"Location": "https://berrys01.s3.ap-south-1.amazonaws.com/Nqc6YL5LG1r3kWZIPigc1.mp4",
"Bucket": "berrys01",
"Key": "Nqc6YL5LG1r3kWZIPigc1.mp4",
"ETag": "\"4fbfb64ae636171fa7a7020ecc3b6a9e-16\""
},
"slug": "hgdsfhgsdf",
"updatedAt": "2022-01-06T18:40:56.963Z",
"createdAt": "2022-01-06T18:40:56.963Z"
},
{
"free_preview": true,
"_id": "61d737cada89b03378321bc5",
"title": "hello",
"content": "dfgdfg",
"video": {
"Location": "https://berrys01.s3.ap-south-1.amazonaws.com/fv5jEXzphsJ9al9DMKAr3.mp4",
"Bucket": "berrys01",
"Key": "fv5jEXzphsJ9al9DMKAr3.mp4",
"ETag": "\"72e0076dec633d7f3630628e92ba1891-3\""
},
"slug": "hello",
"updatedAt": "2022-01-06T18:41:14.132Z",
"createdAt": "2022-01-06T18:41:14.132Z"
},
{
"free_preview": true,
"_id": "61d737d6da89b03378321bc6",
"title": "rgrg",
"content": "dgdf",
"video": {
"Location": "https://berrys01.s3.ap-south-1.amazonaws.com/gmYnDGSrspH4jgfhC8ybr.mp4",
"Bucket": "berrys01",
"Key": "gmYnDGSrspH4jgfhC8ybr.mp4",
"ETag": "\"72e0076dec633d7f3630628e92ba1891-3\""
},
"slug": "rgrg",
"updatedAt": "2022-01-06T18:41:26.610Z",
"createdAt": "2022-01-06T18:41:26.610Z"
},
{
"free_preview": true,
"_id": "61d737e2da89b03378321bc7",
"title": "rgdgry56t5",
"content": "5yr",
"video": {
"Location": "https://berrys01.s3.ap-south-1.amazonaws.com/hzRW7TJn9ichITOk-3A-w.mp4",
"Bucket": "berrys01",
"Key": "hzRW7TJn9ichITOk-3A-w.mp4",
"ETag": "\"72e0076dec633d7f3630628e92ba1891-3\""
},
"slug": "rgdgry56t5",
"updatedAt": "2022-01-06T18:41:38.985Z",
"createdAt": "2022-01-06T18:41:38.985Z"
}
],
From what I see, a solution would be to do something like this
const courses = await Course
.find({ published: true })
.populate({
path: 'lessons',
match: { free_preview: true },
select: 'name -_id'
})
.exec();

filter subdocuments array with mongoose using find()

I have 2 schemas:
const SiteSchema = new mongoose.Schema(
{
placement: Number,
groupId: mongoose.SchemaTypes.ObjectId,
title: {
type: String,
required: true,
trim: true,
},
url: {
type: String,
required: true,
},
},
{ timestamps: true }
)
and
const GroupSchema = new mongoose.Schema(
{
placement: Number,
header: {
type: String,
required: true,
trim: true,
},
items: [Site.schema],
},
{ timestamps: true }
)
I'm trying to get all groups with up to 5 of their corresponding sites based on the sites placement value like this:
roup.find({ 'items.placement': { $lte: 5 } })
.skip(offset)
.limit(maxNumberOfResults)
.sort('placement')
.lean()
.then(groups => {res.send({ sites: groups}))
however the result i get is all the sites in the group, regardless of their placement value.
for example:
I'm expecting to get:
[
{
"_id": "60dd2c314d98940d90fe8861",
"placement": 0,
"createdAt": "some date",
"updatedAt": "some date",
"header": "group",
"items": [
{
"_id": "60dd2cb54d98940d90fefb2a",
"groupId": "60dd2c314d98940d90fe8861",
"placement": 1,
"title": "something",
"url": "some url",
"createdAt": "some date",
"updatedAt": "some date"
},
{
"_id": "60dd2cb54d98940d90fefb2d",
"groupId": "60dd2c314d98940d90fe8861",
"placement": 2,
},
{
"_id": "60dd2cb54d98940d90fefb2f",
"groupId": "60dd2c314d98940d90fe8861",
"placement": 3,
},
{
"_id": "60dd2cb54d98940d90fefb30",
"groupId": "60dd2c314d98940d90fe8861",
"placement": 4,
},{
"_id": "60dd2cb54d98940d90fefb30",
"groupId": "60dd2c314d98940d90fe8861",
"placement": 5,
},
]
but getting placements 6 and onwards as well
***If someone could also tell me how to sort the subdocument array according to the placement value, would be greatly appreciated.
Try changing items: [Site.schema] to items: [SiteSchema],

how to retrieve data from 3 mongoose sachems in custom order

I'm using node, express, mongoose for my back-end. I created User schema as follows,
const mongoose = require('mongoose');
const addressSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
no: { type: String },
firstStreet: { type: String },
secondStreet: { type: String },
city: { type: String, required: true },
district: { type: String }
})
const contactDetailsSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
landNumber: { type: String },
mobileNumber: { type: String },
momNumber: { type: String },
dadNumber: { type: String },
gardianNumber: { type: String }
})
const userSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
email: {
type: String,
required: true,
unique:true,
lowercase: true,
match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
},
password: { type: String, required: true },
role: { type: String, required: true },
fullName: { type: String, required: true },
batch: { type: Number, required: true },
subject: [{
type: String
}],
school: { type: String, required: true },
birthday: { type: String },
address: { type: mongoose.Schema.Types.ObjectId, ref:'User' },
contactDetails: { type: mongoose.Schema.Types.ObjectId, ref:'User' },
stream: { type: String },
});
module.exports = {
user: mongoose.model('User', userSchema),
address: mongoose.model('Address', addressSchema),
contactDetails: mongoose.model('ContactDetails', contactDetailsSchema)
};
and I created a GET route to retrieve data from all users. I store these data in three separate mongoDB collections with same _id. And I want to get those all User data.
my User GET route is like this,
const userModels = require('../models/user');
const User = userModels.user;
const Address = userModels.address;
const ContactDetails = userModels.contactDetails;
router.get('/', (req, res) =>{
User
.find()
.exec()
.then(docs => {
console.log(docs);
const responce1 = {
count: docs.length,
Users: docs.map(doc => {
return {
Message: 'User Details',
Id: doc._id,
Email: doc.email,
Role: doc.role,
Full_Name: doc.fullName,
Batch: doc.batch,
Subject: doc.subject,
School: doc.school,
Birthday: doc.birthday,
Stream: doc.stream,
request: {
type: 'get',
url: 'http://localhost:3000/user/' +doc._id
}
}
})
}
Address
.find()
.exec()
.then(docs => {
console.log(docs)
responce2 = {
count: docs.length,
Address: docs.map(doc => {
return {
Message: 'Address',
_id: doc._id,
Address: doc.city,
First_Street: doc.firstStreet,
Second_Street: doc.secondStreet,
city: doc.city,
District: doc.district,
}
})
}
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
ContactDetails
.find()
.exec()
.then(docs => {
console.log(docs)
responce3 = {
count: docs.length,
ContactDetails: docs.map(doc => {
return {
Message: 'Contact Details',
_id: doc._id,
Land_Number: doc.landNumber,
Mobile_Number: doc.mobileNumber,
Mom_Number: doc.momNumber,
Dad_Number: doc.dadNumber,
Gardian_Number: doc.gardianNumber,
}
})
}
res.status(200).json([responce1,responce2,responce3]);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
I get data like this,
[
{
"count": 3,
"Users": [
{
"Message": "User Details",
"Id": "5b8e68fb9c898543b4970628",
"Email": "new2#gmail.com",
"Role": "student",
"Full_Name": "Dinusha",
"Batch": 16,
"Subject": [
"ICT"
],
"School": "School",
"Birthday": "1996/10/23",
"Stream": "English",
"request": {
"type": "get",
"url": "http://localhost:3000/user/5b8e68fb9c898543b4970628"
}
},
{
"Message": "User Details",
"Id": "5b8e68fd9c898543b4970629",
"Email": "new3#gmail.com",
"Role": "student",
"Full_Name": "Dinusha",
"Batch": 16,
"Subject": [
"ICT"
],
"School": "School",
"Birthday": "1996/10/23",
"Stream": "English",
"request": {
"type": "get",
"url": "http://localhost:3000/user/5b8e68fd9c898543b4970629"
}
},
{
"Message": "User Details",
"Id": "5b8f52e707c299266c0a6b97",
"Email": "new4#gmail.com",
"Role": "student",
"Full_Name": "Dinusha",
"Batch": 16,
"Subject": [
"ICT"
],
"School": "School",
"Birthday": "1996/10/23",
"Stream": "English",
"request": {
"type": "get",
"url": "http://localhost:3000/user/5b8f52e707c299266c0a6b97"
}
}
]
},
{
"count": 3,
"Address": [
{
"Message": "Address",
"_id": "5b8e68fb9c898543b4970628",
"Address": "city",
"city": "city",
"District": "rathnapura"
},
{
"Message": "Address",
"_id": "5b8e68fd9c898543b4970629",
"Address": "city",
"city": "city",
"District": "rathnapura"
},
{
"Message": "Address",
"_id": "5b8f52e707c299266c0a6b97",
"Address": "city",
"city": "city",
"District": "rathnapura"
}
]
},
{
"count": 3,
"ContactDetails": [
{
"Message": "Contact Details",
"_id": "5b8e68fb9c898543b4970628",
"Land_Number": "072846",
"Mobile_Number": "7368438",
"Mom_Number": "7364738",
"Dad_Number": "648364"
},
{
"Message": "Contact Details",
"_id": "5b8e68fd9c898543b4970629",
"Land_Number": "072846",
"Mobile_Number": "7368438",
"Mom_Number": "7364738",
"Dad_Number": "648364"
},
{
"Message": "Contact Details",
"_id": "5b8f52e707c299266c0a6b97",
"Land_Number": "072846",
"Mobile_Number": "7368438",
"Mom_Number": "7364738",
"Dad_Number": "648364"
}
]
}
]
but I need to get data of every User like in this form
[
"Users":
{
"Message": "User Details",
"Id": "5b8e68fb9c898543b4970628",
"Email": "new2#gmail.com",
"Role": "student",
"Full_Name": "Dinusha",
"Batch": 16,
"Subject": [
"ICT"
],
"School": "School",
"Birthday": "1996/10/23",
"Stream": "English",
"request": {
"type": "get",
"url": "http://localhost:3000/user/5b8e68fb9c898543b4970628"
}
},
"Address":
{
"Message": "Address",
"_id": "5b8e68fb9c898543b4970628",
"Address": "city",
"city": "city",
"District": "rathnapura"
},
"ContactDetails":
{
"Message": "Contact Details",
"_id": "5b8e68fb9c898543b4970628",
"Land_Number": "072846",
"Mobile_Number": "7368438",
"Mom_Number": "7364738",
"Dad_Number": "648364"
},
]
can I get those data like that.
how to get data from mongodb as that custom form.
Use aggregate method and $lookup
https://mongoosejs.com/docs/api.html#aggregate_Aggregate-lookup

Resources