Mongodb Search Query with Populate and regex - regex

I want regex search on mongodb with NodeJS.
First One is Users and Second one is categories. Here I have saved categories id in Users
collection. I want a search Query that filter my records.
Users collection
{_id:'mongo_id', name:"User First",cat_id:2}
{_id:'mongo_id', name:"User Second",cat_id:2}
{_id:'mongo_id', name:"User Third",cat_id:1}
{_id:'mongo_id', name:"User Fourth",,cat_id:4}
Categories
Suppose id is numeric. For demo purpose I have written numeric values.
{_id:'1', name:"Salesman",}
{_id:'2', name:"Carpanter"}
{_id:'3', name:"Plumber"}
{_id:'4', name:"Engineer"}
I have a text input if I will type Carpanter or Carpan(regex) then I want 2 records, or
When I type User Second or second I want 1 Record
var query = {
'name': {
$regex: req.body.name,
$options: 'i'
}
};
innerQuery = {
path: 'category',
select: 'name'
}
Users.find(query)
.populate(innerQuery)
.sort({
'createdDate': -1
})

Your user record looks like this:
{_id:'mongo_id': name:"User First",cat_id:2}
I'll assume the extra : is a typo.
Aside from that, you are attempting to query for title. There is no path title in that record, so you can't query for it.
You're also trying to populate the path category, but there is no field with that name in the user records. The only related field I see is cat_id.
If you want to, for example, query by name and populate the cat_id, you can do something like this:
var query = {
'name': {
$regex: req.body.title,
$options: 'i'
}
};
var innerQuery = {
path: 'cat_id',
model: 'Category',
select: 'name'
};
This is entirely dependent on whether you named your model Category, and also what your schemas actually look like.
(PS, you're also trying to sort by createdDate, but I don't see that field in any of your records, either).

Related

Django query annotate and agregate

How can I write a query like this in Django?
select sum(kolvo), reason
from(
select count(reason) kolvo, reason
from contacts group by reason) group by reason
Your query looks semantically equivalent to:
SELECT count(reason) AS kolvo,
reason
FROM contacts
GROUP BY reason
So without the outer query.
You can make such query in Django's ORM with:
Contacts.objects.values('reason').annotate(
kolvo=Count('id')
).order_by('reason')
This will then return a QuerySet that wraps dictionaries, like:
< QuerySet [
{ 'reason': 'some reason', 'kolvo': 13 },
{ 'reason': 'some other reason', 'kolvo': 2 },
] >

ember js get relationships of relationships

My routes have something like this
return this.store.query('author', {filter:{username : username},
include: 'books, books.readers'})
as we can see author has Many-2-Many relationships with books, book have relationship with reader
How can I include books.reader when run query with author?
Ember Data provides the ability to query for records that meet certain criteria. Calling store.query() will make a GET request with the passed object serialized as query params. This method returns a DS.PromiseArray in the same way as findAll.
So for example in your case author with :username can be changed to the following code:
// GET to /persons?filter[username]=username
this.get('store').query('author', {
filter: {
username: username
}
}).then(function(username) {
// Do something with `username` which can be another filter and whatever else you want, give it a try.
});
Hope it can solve your problem.

Associating multiple items with a single REST call

I am using the Loopback framework, and have modelA which is in a many-to-many relation with modelB.
I want to know if it's possible to relate multiple items from modelB to modelA.
There is currently a way to relate one item with this call:
/modelA/{id}/modelB/rel/{fk}
Is there any way to perform this in a bulk operation?
If I understand your question correctly, I think you can simply do it through a filter. ModelA has many modelBs, Let me assume the relation name is 'modelBs'
modelA.find({
where: [your filter option on model A]
include: {
relation: 'modelBs',
scope: {
[your filters on model B]
}
}
})
in restful way:
/modelAs?filter[include]=modelBs&filter[where]....
The official documentation may help: https://docs.strongloop.com/display/public/LB/Querying+data
It seems to be HasManyThrough model.
I believe your model names starts with lowercase but ideally it should be ModelA and ModelB and their instances can then be saved in modelA and modelB variables.
In order to use add method, you will need to first find instance of ModelA first using ModelA.findById which you can save in modelA variable and then use the following code:
modelA.modelBs.add(modelBFieldsObject, function(err, patient) {
...
});
where modelBs should be the name of relation in the ModalA.json file as in
"relations": {
"modelBs": {
"type": "hasMany",
"model": "ModelB",
"foreignKey": "modelAId",
"through": "ModelAModelB",
"keyThrough": "modelBId"
}
...
I think it should be allowed to pass an array of modelBFieldsObject to create multiple instances as in
modelA.modelBs.add([modelBFieldsObject, modelBFieldsObject], function(err, patient) {
...
});
Tip: For clarity, name your models beginning with upper case letter and their instance variable in camelCase format.
References: Methods added to the model.

How do I select records where its related records do not have a specific attribute-value?

I want to select all of the users who do not have associated posts where the title is, 'test123'. The following syntax is not working:
User.includes(:posts).where.not(posts: { title: 'test123' })
How do I select users whose associated posts do not have a specific title?
UPDATE
Originally, I tried to isolate where exactly I thought I was having the problem, but I want to show the query that most closely reflects what I am doing. The problem is still with the, where.not, clause. It's returning an empty array when I know there are records with posts that have other titles.
User.where("users.created_at >= ? and users.created_at <= ?", 1.month.ago.utc, 1.week.ago.utc)
.where(active: true)
.includes(:comments)
.where('comments.id is not null')
.includes(:posts)
.where.not(posts: { title: 'test123'} )
.references(:posts)
From the API Doc
If you want to add conditions to your included models you’ll have to
explicitly reference them
So the below query will work
User.includes(:posts).where.not(posts: { title: 'test123' }).references(:posts)
I believe the problem was with executing inner vs outer joins with Active Record Query Syntax. The problem with this query:
User.includes(:posts).where.not(posts: { title: 'test123' })
is that it evaluates, where.not(posts: { title: 'test123'}), only after retrieving all the user records with an associated post -- leaving behind all of the other user records who do not have a corresponding post. I wanted a query that would not exclude the Users without posts.
This is how I did it:
User.where("users.id NOT IN (SELECT DISTINCT(user_id) from posts where title = 'test123')")

Dropdown list in yii from other controller

I want list all objects of my model, and write to file the id of selected model. Using SiteController I render my page but what model I shall use?
$models = myModel::model()->findAll();
$list = CHtml::listData($models, 'id', 'name');
echo CHtml::dropDownList( ???? , $select, $list);
If I get what you're trying to do, You're talking about two models. Like tbl_product => Product and tbl_category => Category.
For demonstration purpose: Say, you want to create a new product and every product must belong to a category, then you might make use of the active dropdown. Using code similar to yours, you can say:
$category = Category::model()->findAll();
$list = CHtml::listData($category, 'id', 'name');
An important thing to note is that CHtml::activeDropDownList() expects different kinds of arguments. The main difference between it and CHtml::dropDownList() is that activeDropDownList( is tied to a Model while dropDownList() isn't.
public static string activeDropDownList(CModel $model, string $attribute, array $data, array $htmlOptions=array ())
public static string dropDownList(string $name, string $select, array $data, array $htmlOptions=array ())
So, using the example, assuming our Product model has a field called category_id, then the dropdown list would be generated using either:
CHtml::activeDropDownList($model, 'category_id', $list);
or if you've created an Activeform object like this:
$form=$this->beginWidget('CActiveForm');
then you could create the dropDown list like this:
$form->dropDownList($model, 'category_id', $list);
Where $model would be the Product model.
I hope this has been helpful.