Sequelize get own attributes only, ignore included instances - javascript

What I'm looking for is an instance method in Model that will return only the attributes of that model & exclude instances of any included model.
eg: Imagine I have 2 models, with a hasMany ( or any ) association:
Post {
id,
content,
user_id
}
User: {
id,
name,
}
and I have:
const userWithPosts = await User.findOne({
where: { id: 33 },
include: [{
model: Post,
as: 'posts'
}]
});
console.log(userWithPosts)
/*
{
id: 33,
name: 'John Doe',
posts: [
Post {
id: 1,
content: '..',
user_id: 33
},
Post {
id: 2,
content: '...',
user_id: 33
}
]
}
*/
I'm looking for a method, say getOwnAttributes or something like that which does:
userWithPosts.getOwnAttributes()
/*
{
id: 33,
name: 'John Doe',
}
*/
I've looked into couple of things:
userWithPosts.get({ raw: true })
userWithPosts.get({ plain: true })
userWithPosts.toJSON()
All of the above returns included instances as well.
Any existing method or workaround that can do this?
EDIT: I'm not talking about doing it at query time, but getting the value from already queried instance. Currently my work-around for this is:
const payload = _.pick(userWithPosts.toJSON(), [
...Object.keys(User.rawAttributes),
]);

You can refer to the code below to exclude attributes of Post table.
const userWithPosts = await User.findOne({
where: { id: 33 },
include: [{
model: Post,
as: 'posts',
attributes: []
}]
});
I hope it helps!

Related

Edit multiple objects in array using mongoose (MongoDB)

So I tried several ways, but I can't, I can modify several objects with the same key but I can't modify any with different keys, if anyone can help me is quite a complex problem
{
id: 123,
"infos": [
{ name: 'Joe', value: 'Disabled', id: 0 },
{ name: 'Adam', value: 'Enabled', id: 0 }
]
};
In my database I have a collection with an array and several objects inside which gives this.
I want to modify these objects, filter by their name and modify the value.
To give you a better example, my site returns me an object with the new data, and I want to modify the database object with the new object, without clearing the array, the name key never changes.
const object = [
{ name: 'Joe', value: 'Hey', id: 1 },
{ name: 'Adam', value: 'None', id: 1 }
];
for(const obj in object) {
Schema.findOneAndUpdate({ id: 123 }, {
$set: {
[`infos.${obj}.value`]: "Test"
}
})
}
This code works but it is not optimized, it makes several requests, I would like to do everything in one request, and also it doesn't update the id, only the value.
If anyone can help me that would be great, I've looked everywhere and can't find anything
My schema structure
new Schema({
id: { "type": String, "required": true, "unique": true },
infos: []
})
I use the $addToSet method to insert objects into the infos array
Try This :
db.collection.update({
id: 123,
},
{
$set: {
"infos.$[x].value": "Value",
"infos.$[x].name": "User"
}
},
{
arrayFilters: [
{
"x.id": {
$in: [
1
]
}
},
],
multi: true
})
The all positional $[] operator acts as a placeholder for all elements in the array field.
In $in you can use dynamic array of id.
Ex :
const ids = [1,2,..n]
db.collection.update(
//Same code as it is...
{
arrayFilters: [
{
"x.id": {
$in: ids
}
},
],
multi: true
})
MongoPlayGround Link : https://mongoplayground.net/p/Tuz831lkPqk
Maybe you look for something like this:
db.collection.update({},
{
$set: {
"infos.$[x].value": "test1",
"infos.$[x].id": 10,
"infos.$[y].value": "test2",
"infos.$[y].id": 20
}
},
{
arrayFilters: [
{
"x.name": "Adam"
},
{
"y.name": "Joe"
}
],
multi: true
})
Explained:
You define arrayFilters for all names in objects you have and update the values & id in all documents ...
playground

Adding element inside nested array in mongoose

Server Started at Port 3000...
{
_id: new ObjectId("61c707e9f4ff040a47d27c3f"),
username: 'adityaaryam',
password: '1234',
nameOfUser: 'Aditya Aryam',
emailOfUser: 'adityaaryam#gmail.com',
userAllLists: [
{
name: 'Hello',
items: [],
_id: new ObjectId("61c70d915448262d1dca1a69")
},
{
name: 'Work',
items: [],
_id: new ObjectId("61c70d965448262d1dca1a70")
},
{
name: 'Home Work',
items: [],
_id: new ObjectId("61c70d9b5448262d1dca1a79")
},
{
name: 'Hello',
items: [],
_id: new ObjectId("61c70e7f5448262d1dca1a84")
},
{
name: 'Play',
items: [],
_id: new ObjectId("61c7126a5448262d1dca1a9b")
},
{
name: 'Eat',
items: [],
_id: new ObjectId("61c71325b0219e6ce4f57990")
},
{
name: 'Walla',
items: [],
_id: new ObjectId("61c7197de9564390d506cbe9")
}
],
__v: 7
}
This is how my database looks like. I want to push new elements to "items" array which is nested inside the "userAllLists" array using mongoose. How do I implement this?
I have been trying findOneAndUpdate using $push but I am not able to achieve my desriable results.
My Schemas are as follows:
const itemSchema = {
name: String
};
const customListSchema ={
name:String,
items:[itemSchema]
};
const userSchema={
username: String,
password: String,
nameOfUser: String,
emailOfUser: String,
userAllLists: [customListSchema],
};
Thanks in Advance!
I think $push is the right way to push new elements to nested arrays, you didn't show the code you tried to see if it works or not, at all here is an example based on your schema
User.update({_id: "61c707e9f4ff040a47d27c3f", }, {
'$push': {
"userAllLists.$[].items": {name: "test item name"}
}
});
Note: $[] expressions will push the specified object inside all items arrays that exist in userAllLists
To push the item for only specific userAllLists object you can use the following syntax
User.update({_id: "61c707e9f4ff040a47d27c3f", "usersAllLists._id": "61c70d915448262d1dca1a69"}, {
'$push': {
"userAllLists.$.items": {name: "test item name"}
}
});
this will ensure to push the item object to the specified usersAllLists object which has this id 61c70d915448262d1dca1a69

What does this 'child' in my javascript array mean?

I keep getting these 'child' things in my Javascript collection after certain operations. The 'child' keyword is showing up in my terminal after logging the Javascript collection.
Whats strange is that I can't actually find good documentation anywhere online on what this means. Seems like it should be a basic concept.
When I do google it I just get a ton of results for 'child' in context of HTML and the DOM.
What does it mean in javascript? And how could I fix this collection to have these nested collections without the 'child' thing.
Gosh I wish I could speak about it with more sophistication :p
More Context on How This 'Bad' Collection is Generated
So I'm trying to populate JSON data from my Mongodb database and return it to the frontend. Essentially I have nested collections like so:
Institution
|
------------> memberOrganizations
|
---------------------> associatedVIPs
Where I'm originally grabbing Institutions I can populate collections one level down using built in populate functionality.
Doing like so:
Institution.find()
.populate('memberOrganizations')
.then(function (institutions) {
console.log("All institutions, memberOrganizations populated no problem.");
return res.json(institutions);
});
The problem is coming in when I try to go populate collections inside those member organizations, and replace existing memberOrganizations data with that.
Institution.find()
.populate('memberOrganizations')
.then(function (institutions) {
var populateOrganizationOrderManagers = _.map(institutions, function (institution) {
var masterInstitution = _.cloneDeep(institution);
return new Promise(function (resolve, reject) {
var ids = _.map(institution.memberOrganizations, 'id');
Organization.find(ids).populate('associatedVIPs').then(function (orgs) {
masterInstitution.memberOrganizations = orgs;
resolve(masterInstitution);
});
});
});
return Promise.all(populateOrganizationOrderManagers)
.then(function (institutionsWithOrderManagers) {
return res.json(institutionsWithOrderManagers);
});
})
Printouts of the JSON data using console.log to print to my terminal
(Simplified all data by a bit to make it easier to make a point)
What it looks like:
[ child {
memberOrganizations:
[ { associatedVIPs:
[ { firstName: 'Gregory',
lastName: 'Parker',
email: 'info#parker2018.com',
id: '5ab94183164475010026184b' } ],
institution: '5ab940b71644750100261845',
name: 'Greg Parker',
type: 'Student',
id: '5ab941401644750100261847' },
{ associatedVIPs:
[ { firstName: 'Irma',
lastName: 'Francisco',
email: 'irmaf#houstontransporter.com',
id: '5ae348da1ef63b245a74fe2d' } ],
institution: '5ab940b71644750100261845',
name: 'Transporter Inc',
type: 'Other',
id: '5ae3488d1ef63b2c8f74fe29' } ],
name: 'Corporate',
createdAt: 2018-03-26T18:49:27.955Z,
updatedAt: 2018-07-05T15:00:02.562Z,
id: '5ab940b71644750100261845' }
What I'd like it to look like:
{ memberOrganizations:
[ {
name: 'Tau Kappa Epsilon',
type: 'Greek - Fraternity',
institution: '5a3996d47bab3401001cc1bc',
id: '5a3ae7ebdfd69201001aa54d'
associatedVIPs:
[ { firstName: 'Irma',
lastName: 'Francisco',
email: 'irmaf#houstontransporter.com',
id: '5ae348da1ef63b245a74fe2d' },
{ firstName: 'Zach',
lastName: 'Cook',
email: 'zach#google.com',
id: '5ae348da1ef63b245a74f' } ]
},
{ name: 'Farmhouse',
type: 'Greek - Fraternity',
institution: '5a3996d47bab3401001cc1bc',
id: '5a4e71e806b97a01003bd313' } ],
name: 'Troy University',
createdAt: '2017-12-19T22:46:44.229Z',
updatedAt: '2018-07-05T15:18:03.182Z',
id: '5a3996d47bab3401001cc1bc' },
{ memberOrganizations:
[ { name: 'Alpha Epsilon Pi',
type: 'Greek - Fraternity',
institution: '5a4d534606b97a01003bd2f1',
id: '5a4f95c44ec7b6010025d2fb' },
{ name: 'Alpha Delta Chi',
type: 'Greek - Sorority',
institution: '5a4d534606b97a01003bd2f1',
id: '5a74a35e1981ef01001d0633' },
{ name: 'Phi Sigma Kappa',
type: 'Greek - Fraternity',
institution: '5a4d534606b97a01003bd2f1',
id: '5a7ba61821024e0100be67b7' } ],
name: 'University of Alabama',
createdAt: '2018-01-03T22:03:50.929Z',
updatedAt: '2018-07-05T15:18:03.182Z',
id: '5a4d534606b97a01003bd2f1' }

Normalizr: Identifying entities by type rather than schema for polymorphic mappings

For a polymorphic schema such as Union in Normalizr, for schema definitions and data:
const data = { owner: { id: 1, type: 'user', name: 'Anne' } };
const user = new schema.Entity('users');
const group = new schema.Entity('groups');
const unionSchema = new schema.Union({
user: user,
group: group
}, 'type');
const normalizedData = normalize(data, { owner: unionSchema });
normalized data takes the form:
{
entities: {
users: { '1': { id: 1, type: 'user', name: 'Anne' } }
},
result: { owner: { id: 1, schema: 'user' } }
}
The entities are keyed on the schema key, in this case, users, but the result object includes only the key for the schema in the UnionSchema definition. This can make it difficult to match up the elements later without full denormalization.
Is there some better way to normalize such data with normalizr to make it easier to pull the entity from the entities, given the result? For my purposes, ideally, data could be normalized from something like:
const data = { owner: { id: 1, type: 'users', name: 'Anne' } };
to
{
entities: {
users: { '1': { id: 1, type: 'users', name: 'Anne' } }
},
result: { owner: { id: 1, type: 'users' } }
}
Note that the type matches the entity key (that is pretty trivial), and the name of the key in result is type (more of a pain if you want to do it with more complex data). I suspect that that sort of normalization would make it harder to denormalize, but I'm interested in normalization only.
Got an answer on this:
https://github.com/paularmstrong/normalizr/issues/281
Apparently, the behavior is intentional and is not going to change--there is no way to use Normalizr to do what I asked.

Sails Js populate don't retrieve all attributes

I have a problem with populate. I made a query to get User, Project and Topic information (Those are my 3 models). I need to show multiples dates in profile view. This is my code:
Project.js:
module.exports = {
attributes: {
name: {
type: "string"
},
topics: {
collection: "topic",
via: "projects"
},
members: {
collection: "user",
via: "projects"
},
content: {
collection: "content",
via: "projectData"
}
}
};
Topic.js:
module.exports = {
attributes: {
name: {
type: "string"
},
projects: {
collection: "project",
via: "topics"
}
}
};
in User.js:
show: function(req, res, next) {
User.findOne({id: req.session.User.id}).populateAll().exec(function prjFound(err, user){
if (err) return next(err);
if (!user) return next();
console.log(user);
res.view({
user: user
});
});
},
Console print this:
{ projects:
[ { name: 'Fran',
createdAt: '2017-06-19T21:33:17.152Z',
updatedAt: '2017-06-19T21:33:17.190Z',
id: 97 },
{ name: 'River Plate',
createdAt: '2017-06-19T21:36:38.757Z',
updatedAt: '2017-06-19T21:36:38.798Z',
id: 98 },
{ name: 'Guido',
createdAt: '2017-06-20T01:33:53.843Z',
updatedAt: '2017-06-20T01:33:53.926Z',
id: 99 } ],
group: [],
mat: 222222,
name: 'Francisco',
lastname: 'P',
email: 'fran#1.com.ar',
encryptedPassword: '$2a$10$nKp/eAOCDPw4BS.PvQCThe42wa2/8ZABw4JzA0no9GPVT4VjFl3ZO',
createdAt: '2017-06-19T21:32:10.535Z',
updatedAt: '2017-06-19T21:32:10.535Z',
id: '594842da6aeecd880ebab4e6'
}
I want to get all atributes of project model (Content, topic, and members), not only the name and id.
Anyone can explain Why my code is wrong?
Sails/Waterline populate/populateAll do 1 level of population. For 2 or deeper level you need to write code for it.
E.g. Gather ids of user's project and do populateAll on Project.find
Sailsjs doesn't currently support population within a populated field. Write a query in the returned response and append it to the field that you want to populate, send the response with your desired results.
Check this.
let result = await model.find(filter).populate("fieldName", {select:['attribute1','attribute1']})

Categories

Resources