Access to table user in sequelize - javascript

How can I get the information of 2 users when I request my friends table?
My table friends is formatted like this:
id X , UserId : 1 , idFriend : 3, ...
My table User is formatted like this:
id X , name , mail , ...
When I link model user in my query, I get only the information of UserID, but I don't get the information on idFriend
My request is
models.Friend.findAll({
where: {
$or: [{
idFriend: userFound.id
},
{
UserID: userFound.id
}],
status: "pending"
},
include: [
{ model: models.User },
]
})
How can I do that ?

1st Define association like this in your friend model :
Friend.belongsTo(User, { foreignKey : 'UserID', constraints: false});
Friend.belongsTo(User, { as: 'friend', foreignKey : 'idFriend' , constraints:false});
2nd thing is include model like this :
models.Friend.findAll({
where: {
$or: [{
idFriend: userFound.id
},
{
UserID: userFound.id
}],
status: "pending"
},
include: [
{
model: models.User ,
required : false,
where : { id : userFound.id }
},{
model: models.User ,
as : 'friend', // <--------- Magic is here
required : false,
where : { id : userFound.id }
}
]
})

Related

mongoose update nested document not working

I try to figure out what I'm doing wrong that moongose is not updating my document. Just for testing the id's are hardcoded.
node.js
var id1 = "592fd471fedd311d5c76a024";
var id2 = "592fd4ad608e001d79938ba8";
Workshop.update({
_id: id1,
'themen._id': id2
}, {
'$set': {
'themen.$.risikolandschaft': ["John", "Doe"],
}
},
function(err, body) {
if (err) {
console.log(err)
} else {
console.log(body);
}
}
);
here my data copied from MongoDB Compass
{
"_id" : ObjectId("592fd471fedd311d5c76a024"),
"clientid" : "592cff8794738f0347609666",
"bezeichnung" : "Workshop 1.5.2017 / 10:46",
"themen" : [
{
"thema" : {
"__v" : 0,
"bezeichnung" : "Sturm",
"beschreibung" : "Text",
"_id" : "59255757b1485d0ad2a6924f"
},
"risikolandschaft" : [ "one", "two", "three"],
"date" : "2017-06-01T08:47:41.944Z",
"_id" : ObjectId("592fd4ad608e001d79938ba8")
}
], ...
the log from body
{ n: 0, nModified: 0, ok: 1 }
for adding a new item to the "themen" subdocument i use this:
var new_thema = {
_id: mongoose.Types.ObjectId(),
date : req.body.date,
risikolandschaft : req.body.risikolandschaft,
thema : req.body.thema };
here the mongoose schema
var WorkshopSchema = mongoose.Schema({
clientid: {
type: String,
required: true
},
bezeichnung: {
type: String,
required: true
},
stammdaten : [],
date : Date,
themen : []
});
and there is no subschema for "themen"
"mongoose": "^4.8.6"

Sequelize conditional inclusion of where clause nodejs

I have this code, which has multiple where clause:
Time_Sheet_Details.findAll({
include: [
{
model: timesheetNotesSubcon,
required: false,
attributes:["note","file_name", "id", "working_hrs", "timestamp", "has_screenshot", "notes_category"]
},
{
model: Timesheet,
attributes:["id","leads_id","userid"],
where: {leads_id: filters.leads_id}, // Client
include:[
{
model: Lead_Info, attributes:["id","fname","lname","email","hiring_coordinator_id","status"],
where: {hiring_coordinator_id: {$in: filters.sc_id}}, // SC
include:[{
model: adminInfoSchema,
required: false,
attributes:["admin_id","admin_fname", "admin_lname", "admin_email", "signature_contact_nos", "signature_company"],
}]
},
{
model:Personal_Info,attributes:["userid","fname","lname","email"],
where: {userid: filters.subcon_id}, // Subcon
}
]
}],
where: {
reference_date: filters.reference_date
},
order:[
["id","DESC"]
],
offset:((page-1)*limit),
limit : limit,
subQuery:false
}).then(function(foundObject){
willFulfillDeferred.resolve(foundObject);
});
The where clause is the one with the comment Client, SC and Subcon. However, what is the best approach if those where clause is optional? I am using that for search filter. So if filters.leads_id is null then the where: {leads_id: filters.leads_id}, // Client should not be included in the query. Same with the others. The only solution I can think of is repeat those code blocks for each scenario of not null parameters but that's to repetitive and not practical.
Any other approach or solutions?
If I understand correctly, I think as a first step, you should define your respective where clauses, conditionally upon wether or not each specific search criteria is set:
const clientWhere = filters.leads_id ? {leads_id: filters.leads_id} : {}
const scWhere = filters.sc_id ? {hiring_coordinator_id: {$in: filters.sc_id}} : {}
const subconWhere = filters.subcon_id ? {userid: filters.subcon_id} : {}
So at this point if a search option isn't set, there'll just be an empty object as the where clause.
Next, use those pre-defined where clause objects in your query:
Time_Sheet_Details.findAll({
include: [
{
model: timesheetNotesSubcon,
required: false,
attributes:["note","file_name", "id", "working_hrs", "timestamp", "has_screenshot", "notes_category"]
},
{
model: Timesheet,
attributes:["id","leads_id","userid"],
where: clientWhere, // Client
include:[
{
model: Lead_Info, attributes:["id","fname","lname","email","hiring_coordinator_id","status"],
where: scWhere, // SC
include:[{
model: adminInfoSchema,
required: false,
attributes:["admin_id","admin_fname", "admin_lname", "admin_email", "signature_contact_nos", "signature_company"],
}]
},
{
model:Personal_Info,attributes:["userid","fname","lname","email"],
where: subconWhere, // Subcon
}
]
}],
where: {
reference_date: filters.reference_date
},
order:[
["id","DESC"]
],
offset:((page-1)*limit),
limit : limit,
subQuery:false
}).then(function(foundObject){
willFulfillDeferred.resolve(foundObject);
});

Meteor: How can i push items to users collections and create a list or array instead of replacing each item with the new one?

I'm trying to attach objects from another collection to the Meteor.user collection by a click event. I have a collection with a list of items called "categories" each category has a name field, its that name i want to push into the meteor.user.
Its supposed to work in a way that the user can push as many of these names as they want however its only accepting one entry, and when i click on another name, the new name replaces the old one, instead of being an array. how can i make it so that it can allow many entries?
client/users.js
Template.CategoriesMain.events({
'click .toggle-category': function(e){
//var id = $(e.target).attr('posts.name');
var id = $(e.target).parent().find("a").text();
console.log(id);
e.preventDefault();
Meteor.call('addingCategory', id, function(error, user){ console.log(id)});
}
});
server/users.js
Meteor.methods({
addingCategory: function(name) {
var cats = [{}];
cats.push(name);
console.log(Meteor.userId());
Meteor.users.update({
_id: Meteor.userId()
}, {
$set: {
name: name
}
});
}
});
and this is the user from db.user.find() as you can see with
"name" : "a-reece"
its clearly pushing the name but i cannot add more, i can only replace
{ "_id" : "4CHcZjSD4hCrqweGA", "createdAt" :
ISODate("2016-07-13T21:38:59.505Z"), "services" : { "password" : {
"bcrypt" :
"$2a$10$lKZtrYSMD4EGPj6eamgFDuPZ41Jw52DgivBly3lUYWbGDtfZBg1X." },
"resume" : { "loginTokens" : [ { "when" :
ISODate("2016-07-13T21:38:59.719Z"), "hashedToken" :
"BsqTGedB2FkmSPO3+5I31rOM2+MPtF97Zc9tRQ4pf8Y=" } ] } }, "emails" : [ {
"address" : "mun#les.com", "verified" : false } ], "roles" : [
"discoveror", "yes" ], "isAdmin" : true, "name" : "a-reece" }
how can i add more names instead of replacing?
EDIT
Meteor.methods({
addingCategory: function(name) {
//Meteor.users.update(Meteor.userId(), { $addToSet: { name: name} } );
console.log(Meteor.userId());
//Meteor.users.update(Meteor.userId(), { $set: { "categories": cats }} );
Meteor.users.update({
_id: Meteor.userId()
},
{
$unset: {
name: name
}
},
{
$addToSet: {
name: name
}
});
}
});
ANSWER
Template.CategoriesMain.events({
'click .toggle-category': function(e){
//var id = $(e.target).attr('posts.name');
var ob = $(e.target).parent().find("a").text();
var id = $.makeArray( ob );
console.log(id);
e.preventDefault();
Meteor.call('addingCategory', id, function(error, user){ console.log(id)});
}
});
You're currently doing:
Meteor.users.update({ _id: Meteor.userId() }, { $set: { name: name } });
You have two choices: $push or $addToSet:
Meteor.users.update({ _id: Meteor.userId() }, { $push: { name: name } });
or
Meteor.users.update({ _id: Meteor.userId() }, { $addToSet: { name: name } });
The former pushes onto an array, allowing duplicates, the latter avoids dupes.
You don't need:
var cats = [{}];
cats.push(name);

How to sort inner array and match elements in mongoose

So I am trying to do a semi-complicated query in mongoose. It is as follows:
Event.findOne({ users: { $elemMatch: { user: someUserId, going: 1 }, sort: {createTime: -1} } }
Basically what I would like to do is find a single Event that has a user in its user array that matches an Id and is attending. I have multiple user records for each user in the user array so I want to find the most recent one, to do this I would like to sort the user array by createTime. This is where the error is coming in and it just returns undefined. It works just fine when I don't include the sort function, is there any way to include that?
Here is what my Event object looks like:
{
_id: 1,
endTime: 1429060173865,
createTime: 1429051773902,
startTime: 1429052973865,
description: 'some desc',
creator: 2,
users:
[ { user: 1,
status: 1,
going: 1,
createTime: 1429051773749,
_id: 552d997d8e923847306e2c21 },
{ user: 1,
status: 1,
going: 1,
createTime: 1429051773922,
_id: 552d997d8e923847306e2c25 },
{ user: 1,
status: 9,
going: 0,
createTime: 1429051773942,
_id: 552d997d8e923847306e2c26 } ],
destroyed: 0 }
Is there any way to make this query entirely in mongoose?
As part of find, MongoDB can't sort an array field of a document. You could define a virtual of Mongoose to return the array in sorted order. You could also maintain the array in sorted order, as shown below:
> db.test.drop()
// note: not in order when inserted
> db.test.insert({ "_id" : 0, "users" : [
{ "user" : 1, "going" : 1, "created" : 22 },
{ "user" : 2, "going" : 1, "created" : 775 },
{ "user" : 1, "going" : 1, "created" : 6432 }
] })
// insert user to array and sort as part of update
> db.test.update({ "_id" : 0 },
{ "$push" : {
"users" : {
"$each" : [{ "user" : 2, "going" : 1, "created" : 5532 }],
"$sort" : { "created" : -1 }
}
} })
> > db.test.findOne()
{
"_id" : 0,
"users" : [
{ "user" : 1, "going" : 1, "created" : 6432 },
{ "user" : 2, "going" : 1, "created" : 5532 },
{ "user" : 2, "going" : 1, "created" : 775 },
{ "user" : 1, "going" : 1, "created" : 22 }
]
}
That way, when you perform your find query, the arrays in the matching documents will already be in the desired order.
Your query is not correctly written. In order to sort you should write it in third argument of find:
Event.findOne(
{ users:
{ $elemMatch: { user: someUserId, going: 1 }}
},
null,
{
sort: {createTime: -1}
},
function(err, event) {
//your event here
});

MongoDB, remove object from array

Doc:
{
_id: 5150a1199fac0e6910000002,
name: 'some name',
items: [{
id: 23,
name: 'item name 23'
},{
id: 24,
name: 'item name 24'
}]
}
Is there a way to pull a specific object from an array? I.E. how do I pull the entire item object with id 23 from the items array.
I have tried:
db.mycollection.update({'_id': ObjectId("5150a1199fac0e6910000002")}, {$pull: {id: 23}});
However I am pretty sure that I am not using 'pull' correctly. From what I understand pull will pull a field from an array but not an object.
Any ideas how to pull the entire object out of the array.
As a bonus I am trying to do this in mongoose/nodejs, as well not sure if this type of thing is in the mongoose API but I could not find it.
try..
db.mycollection.update(
{ '_id': ObjectId("5150a1199fac0e6910000002") },
{ $pull: { items: { id: 23 } } },
false, // Upsert
true, // Multi
);
I have a document like
I have to delete address from address array
After searching lots on internet I found the solution
Customer.findOneAndUpdate(query, { $pull: {address: addressId} }, (err, data) => {
if (err) {
return res.status(500).json({ error: 'error in deleting address' });
}
res.json(data);
});
my database:
{
"_id" : ObjectId("5806056dce046557874d3ab18"),
"data" : [
{ "id" : 1 },
{ "id" : 2 },
{ "id" : 3 }
]
}
my query:
db.getCollection('play_table').update({},{$pull:{"data":{"id":3}}},{multi:true}
output:
{
"_id" : ObjectId("5806056dce046557874d3ab18"),
"data" : [
{ "id" : 1 },
{ "id" : 2 }
]
}
You can try it also:
db.getCollection('docs').update({ },{'$pull':{ 'items':{'id': 3 }}},{multi:true})
For a single record in array:
db.getCollection('documents').update(
{ },
{'$pull':{ 'items':{'mobile': 1234567890 }}},
{new:true}
);
For a multiple records with same mobile number in array:
db.getCollection('documents').update(
{ },
{
$pull: {
items: { mobile: 1234567890 }
}
},
{ new:true, multi:true }
)
Use $pull to remove the data
return this.mobiledashboardModel
.update({"_id": args.dashboardId}, { $pull: {"viewData": { "_id": widgetId}}})
.exec()
.then(dashboardDoc => {
return {
result: dashboardDoc
}
});
Kishore Diyyana:
If you want to remove all elements including the key of the element attributes list.
Here is the example of mongoDB unset operator:
db.UM_PREAUTH_CASE.update(
{ 'Id' : 123}, { $unset: { dataElements: ""} } )
JSON Look like this:
{ "Id":123,"dataElements" : [ { "createdBy" : "Kishore Babu Diyyana", "createdByUserId" : 2020 }, { "createdBy" : "Diyyana Kishore", "createdByUserId" : 2021 } ] }

Categories

Resources