How to get multiple association results in sequelize - node.js

i have problem fetching the association results.
I have two models
1 - User
2 - Project
User.hasMany(Project, { foreignKey : 'user_Id' });
Project.belongsTo(User, { foreignKey: { name: 'user_Id', type: DataTypes.UUID } })
when i fetch data through Project Model then corresponding user info is also fetched.
getAllProjects: async (req, res) => {
const projects = await Project.findAll({ include: User});
res.json({projects})
}
Result of above code
results
{
"projects": [
{
"id": "9bb3b99c-ac14-48fa-a0f2-e707f1d517ad",
"name": "this is project name",
"budget": "$34",
"details": null,
"days": null,
"deadline": null,
"user_Id": "02ef60af-0b1e-45e9-b393-55e124673143",
"start_date": null,
"status": 0,
"createdAt": "2022-03-23T03:02:56.000Z",
"updatedAt": "2022-03-23T03:02:56.000Z",
"User": {
"id": "02ef60af-0b1e-45e9-b393-55e124673143",
"name": null,
"email": null,
"password": null,
"userType": "client",
"createdAt": "2022-03-23T03:02:35.000Z",
"updatedAt": "2022-03-23T03:02:35.000Z"
}
}
]
}
But in reverse when i try to fetch user with their projects, user info is fetched but the associated projects are not fetched.
Code
getAllUsers: async (req, res) => {
const users = await User.findAll({inlcude: [{model: Project}]})
res.json({users})
}
** Result of above code**
{
"users": [
{
"id": "02ef60af-0b1e-45e9-b393-55e124673143",
"name": null,
"email": null,
"password": null,
"userType": "client",
"createdAt": "2022-03-23T03:02:35.000Z",
"updatedAt": "2022-03-23T03:02:35.000Z"
}
]
}
Please help me. Thanks in advance.

Simply correct typo from inlcude to include.
const users = await User.findAll({include: [{model: Project}]})

Related

How to delete documents from two collections in mongodb

As of now I am able to delete the specific files from filestorage.files collection based on query but I am trying to delete the specific chunks from filesstorage.chunks collection based on files_id. Can someone please suggest me the good approach to achieve it.
Should I use aggregations ? or any looping mechanism ?
Please find the below details
filestorage.files collection:
[{
"_id": {
"$oid": "635a68aa0651c2d869fc3fd3"
},
"length": 878669,
"chunkSize": 261120,
"uploadDate": {
"$date": {
"$numberLong": "1666869418612"
}
},
"filename": "pexels-lucie-liz-3165335_2022-10-27T11-16-58.jpg",
"contentType": "image/jpeg",
"metadata": {
"originalname": "pexels-lucie-liz-3165335.jpg",
"parentFolder": {
"$oid": "636cd238692344da47f3e301"
},
"path": "files/Folder1/Folder3/pexels-lucie-liz-3165335_2022-10-27T11-16-58.jpg"
}
},
{
"_id": {
"$oid": "635a68aa0651c2d869fc3fd4"
},
"length": 878669,
"chunkSize": 261120,
"uploadDate": {
"$date": {
"$numberLong": "1666869418612"
}
},
"filename": "nature-3165335_2022-10-27T11-16-58.jpg",
"contentType": "image/jpeg",
"metadata": {
"originalname": "nature-3165335.jpg",
"parentFolder": {
"$oid": "636cd238692344da47f3e301"
},
"path": "files/Folder1/Folder3/nature-3165335_2022-10-27T11-16-58.jpg"
}
}]
filestorage.chunks collection :
[{
"_id": {
"$oid": "635a68aa0651c2d869fc3fe6"
},
"files_id": {
"$oid": "635a68aa0651c2d869fc3fd3"
},
"n": 0,
"data": {
"$binary": {
"base64" : "xyz"
"subType": "00"
}
}
},
{
"_id": {
"$oid": "635a68aa0651c2d869fc3fd5"
},
"files_id": {
"$oid": "635a68aa0651c2d869fc3fd3"
},
"n": 0,
"data": {
"$binary": {
"base64" : "abcd"
"subType": "00"
}
}
}]
Here is what I have tried :
delete_folder_files: async (ctx:any) => {
// here I am able to delete all the files but confused how to connect chunks schema and delete chunks // based on files_id.
await FileStorage.deleteMany({'metadata.parentFolder': ctx.params.id});
await FileChunk.deleteMany({files_id : ? })
ctx.status = HttpStatusCode.OK;
}
As I can see you are deleting the file ids . So after that you do not have any relation to delete the chunks in fileChunk collection .
Here is what I am thinking , First get all the file ids as an array and later you can delete the chunks with the folder_ids by querying them as array.
const file_ids = await FileStorage.find({'metadata.parentFolder': ctx.params.id },{_id:1}).distinct('_id');
await FileStorage.deleteMany({'metadata.parentFolder':ctx.params.id });
await FileChunk.deleteMany({files_id:{$in:file_ids}});
Note : Please check the performance of the query by uploading multiple files.

How to use both 'include' and 'attributes' in 'findByPk' statement in Sequelize?

How to use both 'include' and 'attributes' in 'findByPk' statement in Sequelize. This is my code:
exports.findOne = (req, res) => {
var id = req.params.id;
User.findByPk(id,
{
include: ["roles"]
},
{
attributes: {
exclude: ['password']
}
}
)
.then(data => {
res.send({"data": data, "resultCode": 1, "message": ""});
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving users."
});
});;
}
But it only works when I use 1 of 2 only.
If I just use: attributes: { exclude: ['password']} the result is as follows:
{
"data": {
"id": 1,
"username": "admin",
"email": "admin#gmail.com",
"createdAt": "2021-09-27T04:22:56.660Z",
"updatedAt": "2021-09-27T04:22:56.660Z"
},
"resultCode": 1,
"message": ""
}
If I just use: {include: ["roles"]} so the result is as follows
{
"data": {
"id": 1,
"username": "admin",
"email": "admin#gmail.com",
"password": "$2a$08$m54ioIwzpZRVC9/HqkHyqezOornjmvT9pDEJcOhHbNcSmLOfw3Sg.",
"createdAt": "2021-09-27T04:22:56.660Z",
"updatedAt": "2021-09-27T04:22:56.660Z",
"roles": [
{
"id": 2,
"name": "moderator",
"createdAt": "2021-09-27T04:20:46.956Z",
"updatedAt": "2021-09-27T04:20:46.956Z",
"user_roles": {
"createdAt": "2021-09-27T04:22:56.791Z",
"updatedAt": "2021-09-27T04:22:56.791Z",
"roleId": 2,
"userId": 1
}
},
{
"id": 3,
"name": "admin",
"createdAt": "2021-09-27T04:20:46.956Z",
"updatedAt": "2021-09-27T04:20:46.956Z",
"user_roles": {
"createdAt": "2021-09-27T04:22:56.791Z",
"updatedAt": "2021-09-27T04:22:56.791Z",
"roleId": 3,
"userId": 1
}
}
]
},
"resultCode": 1,
"message": ""
}
How to use both in my code? Because I dont want to show 'password' field in my result but I want to show the roles of user in my result. How to do like that. Thanks you in advanced
Options should be in 1 object like this.
User.findByPk(id,
{
include: ["roles"],
attributes: {
exclude: ['password']
}
})

fetch array based length - mongoose

I have visitors array. Based on length I want to fetch first 40(highest visted) videos. Is there any query in mongoose for this?
"videos": [],
"description": "Runs for indai",
"status": 1,
"_id": "5e68ee512d3fe53a4426fea5",
"likes": [],
"visited": [{
"_id": "5e690d28797f5b05e066104d",
"user": "::1"
},
{
"_id": "5e690d14797f5b05e066104c",
"user": "::1"
},
{
"_id": "5e690cf7797f5b05e066104b",
"user": "::1"
}],
"comments": [],
"embed": "https://wwdalkfa.com/idaa/46221",
"category": "Mathrubhumi",
"title": "Bdis idnc - Aria.",
"link": "https://www.mdaoa.com/video/46221/dafa",
"image": "https://www.mdaoa.com/media/videos/dstmb1/46221/1b.jpg",
"keywords": "adjal","DAfa",
"__v": 0
controller
exports.getTrendingVideos = async (req, res) => {
try {
const videos = await Video.find().limit(40);
res.send(videos);
} catch (error) {}
};
First, get the length of the array and then sort it, You can do it like this
const videos = await Video.aggregate([
{ $project: { visitedCount: { $size: '$visited' } } },
{ $sort: { $visitedCount: -1 } },
]).limit(40);

How can I populate "oem, category, subcategory" of the product array in the example document:

This is my router JS where I get document by Mongoose. So the thing is i have these nested data like oem, category and subcategory which I cannot get the whole details. I have been trying since one week but nothing complies with me. Can someone please help me out?
router.get("/product/:id/:product_id", (req, res) => {
ProReg.findById(req.params.id)
.populate({
path: "products",
populate: [
{
path: "products.oem",
model: "company",
select: "companyname"
},
{
path: "category",
model: "productcategory",
select: "category"
},
{
path: "subcategory",
model: "productsubcategory",
select: "subcategory"
}
]
})
.exec(function(err, products) {
if (err) {
res.json(err);
} else {
res.json(products);
}
});
});
This is the result that I am getting
{
"_id": "5cd37f4fcd79b01040124dbc",
"refno1": "klklklkl",
"refno2": "klklklkl",
"date": "2019-05-08T00:00:00.000Z",
"customer": "5c98bb0a42207b16d8fbd3cf",
"customertype": "5c7a1a1d4913fa08ac75c027",
"department": "5cbd67c709aeca1ea480157a",
"products": [],
"__v": 3
}
The details of the product is not coming only. Now how can i get this product data along with the details of oem, category, and subcategory?
Without Populate this is the result:
{
"_id": "5cd37f4fcd79b01040124dbc",
"refno1": "klklklkl",
"refno2": "klklklkl",
"date": "2019-05-08T00:00:00.000Z",
"customer": {
"_id": "5c98bb0a42207b16d8fbd3cf",
"customername": "Raghav"
},
"customertype": {
"_id": "5c7a1a1d4913fa08ac75c027",
"customertype": "Government "
},
"department": {
"_id": "5cbd67c709aeca1ea480157a",
"department": "Hardware"
},
"products": [
{
"warrantyfrom": "2019-05-09T00:00:00.000Z",
"warrantyto": "2019-05-30T00:00:00.000Z",
"oemwarrantyfrom": "2019-05-14T00:00:00.000Z",
"oemwarrantyto": "2019-05-14T00:00:00.000Z",
"_id": "5cd37f60cd79b01040124dbd",
"oem": "5cb6e026042460131454cf45",
"category": "5c960902e5cf3429e06beb6c",
"subcategory": "5ca35fbed6e1430df88954a6",
"modelno": "A123888",
"serialno": "fdsfdsfs"
},
{
"warrantyfrom": "2019-05-09T00:00:00.000Z",
"warrantyto": "2019-05-30T00:00:00.000Z",
"oemwarrantyfrom": "2019-05-14T00:00:00.000Z",
"oemwarrantyto": "2019-05-14T00:00:00.000Z",
"_id": "5cd37f65cd79b01040124dbe",
"oem": "5cb6e026042460131454cf45",
"category": "5c960902e5cf3429e06beb6c",
"subcategory": "5ca35fbed6e1430df88954a6",
"modelno": "A123888",
"serialno": "eeeeee"
},
{
"warrantyfrom": "2019-05-09T00:00:00.000Z",
"warrantyto": "2019-05-30T00:00:00.000Z",
"oemwarrantyfrom": "2019-05-14T00:00:00.000Z",
"oemwarrantyto": "2019-05-14T00:00:00.000Z",
"_id": "5cd37f6fcd79b01040124dbf",
"oem": "5c986a1e9b6bc614b8a551b9",
"category": "5c960902e5cf3429e06beb6c",
"subcategory": "5ca35fbed6e1430df88954a6",
"modelno": "QW123",
"serialno": "hhhhhh"
}
],
Did you try simply doing this?
ProReg.findById(req.params.id)
.populate('products.oem')
.populate('products.category')
.populate('products.subcategory')
.exec(function(err, products) {
if (err) {
res.json(err);
} else {
res.json(products);
}
});
});
Check out these related tickets:
Mongoose populate within an object?
Mongoose populate with array of objects containing ref

Mongoose Querying Sub-Document Properties

I am trying to expose this functionality through a WEB API. The way it is set up in this code is that someone does a GET on URL providing a querystring along with it in the form of:
?field=value&anotherfield.subproperty=value
But I can't seem to get querying based on sub-document properties to work. Below you will find my barebones code, record I'm trying to receive and both of my test cases.
Code:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var config = require('../config');
var User = require('../models/user');
var functions = require('../functions');
router.get('/', function(req,res,next) {
//Check Permissions associated with UID *TODO
var parameters = req.query;
console.log(parameters);
User.find(parameters, function(err, users) {
if (err)
{
json = functions.generateOperationOutcome("exception","error",err,"exception");
res.status(500);
res.json(json);
}
else
{
//Check for blank result
if (users.length === 0)
{
json = functions.generateOperationOutcome("not-found","warning","Non-Existent Resource","warning");
res.status(404);
res.json(json);
}
else {
res.status(200);
res.json(users);
}
}
});
});
Record:
{
"_id": "5871d2e814946a941d8611fb",
"resourceType": "testResource",
"link": [],
"communication": [],
"animal": {
"genderStatus": {
"coding": []
},
"breed": {
"coding": []
},
"species": {
"coding": []
}
},
"contact": [],
"photo": [],
"maritalStatus": {
"coding": []
},
"address": [],
"gender": "unknown",
"telecom": [
{
"system": "phone",
"value": "2019196553",
"use": "home"
}
],
"name": {
"suffix": [],
"prefix": [],
"given": [],
"family": []
},
"identifier": [
{
"use": "official",
"type": {
"coding": {
"system": "kylec laptop",
"version": "0.01",
"code": "UDI",
"display": "Universal Device Identifier",
"userSelected": false
},
"text": "test"
},
"system": "test system",
"value": "test value",
"assigner": {
"reference": "test assigner reference"
},
"period": {
"start": "1992-12-31T09:59:59+00:00"
}
}
]
}
Successful Query:
GET http://{{LOCAL}}/api/user?resourceType=testResource
Returns this one model from MongoDB.
Unsuccessful Query (no documents matching query found):
GET http://{{LOCAL}}/api/user?telecom.system=phone
Returns no models back and results in a 404.
You are not properly using dot-notation, as the property you're seeking is within an array:
"telecom": [
{
"system": "phone",
"value": "2019196553",
"use": "home"
}
]
Querying array content typically would require you to do a join against the array (for DocumentDB queries), and not a simple find().
If you wanted the ability to use dot-notation here, you'd need to create a subdocument, like:
"telecom": {
"system": "phone",
"value": "2019196553",
"use": "home"
}
At this point, you'd be able to address properties such as telecom.system, telecom.value, and telecom.use.

Resources