Fulltext mongodb $text search query in graphql-compose-mongoose - graphql-compose-mongoose

I'm unable to figure out how to construct a graphql query for performing the mongodb fulltext search using the text index. https://docs.mongodb.com/manual/text-search/
I've already created a text index on my string in the mongoose schema but I don't see anything in the schemas that show up in the grapqhl playground.

A bit late, though I was able to implement it like so
const FacilitySchema: Schema = new Schema(
{
name: { type: String, required: true, maxlength: 50, text: true },
short_description: { type: String, required: true, maxlength: 150, text: true },
description: { type: String, maxlength: 1000 },
location: { type: LocationSchema, required: true },
},
{
timestamps: true,
}
);
FacilitySchema.index(
{
name: 'text',
short_description: 'text',
'category.name': 'text',
'location.address': 'text',
'location.city': 'text',
'location.state': 'text',
'location.country': 'text',
},
{
name: 'FacilitiesTextIndex',
default_language: 'english',
weights: {
name: 10,
short_description: 5,
// rest fields get weight equals to 1
},
}
);
After creating your ObjectTypeComposer for the model, add this
const paginationResolver = FacilityTC.getResolver('pagination').addFilterArg({
name: 'search',
type: 'String',
query: (query, value, resolveParams) => {
resolveParams.args.sort = {
score: { $meta: 'textScore' },
};
query.$text = { $search: value, $language: 'en' };
resolveParams.projection.score = { $meta: 'textScore' };
},
});
FacilityTC.setResolver('pagination', paginationResolver);
Then you can assign like so
const schemaComposer = new SchemaComposer();
schemaComposer.Query.addFields({
// ...
facilities: Facility.getResolver('pagination')
// ...
});
On your client side, perform the query like so
{
facilities(filter: { search: "akure" }) {
count
items {
name
}
}
}

Related

Unknown column in sequelize count

I do such node.js Sequelize query to get rows quantity of included unread_messages, so I can get amount of unread messages of specifi user. But it returns me Unknown column 'unread_messages.id' in 'field list'.
If I remove attributes: {...} error disappears
const result = await Chats.findAndCountAll({
attributes: {
include: [[Sequelize.fn('COUNT', Sequelize.col('unread_messages.id')), 'total_unread_messages']]
},
where: {
...(req.query.filters as WhereOptions),
},
include: [
{ model: Users, as: 'createdBy', required: false },
{ model: ChatTypes, as: 'type', required: false },
{
model: ChatMessages,
as: 'unread_messages',
where: {
id: {[Op.gt]: Sequelize.literal(`(
SELECT last_read_message_id
FROM chats_users
WHERE
user_id = '${req.user?.id}'
AND
chat_id = Chats.id
)`),}
},
required: false,
},
{
model: ChatMessages,
as: 'last_message',
required: false,
include: [
{ model: Users, as: 'to_user' },
{ model: Users, as: 'from_user' },
{ model: Chats, as: 'chat' },
{ model: MessageTypes, as: 'message_type' },
{
model: Users,
as: 'is_mine',
required: false,
where: { id: req.user?.id },
},
],
},
],
group:['chats.id'],
order: req.query.sort as Order,
offset,
limit,
});

Fuzzy search using mongoose from vue client

Getting error unknown top level operator $regex
search.vue `
let questDocuments = await conversation
.find({ query: { $limit: 100, $search: q, skippop: true } })
.then(response => {`
q is the string being passed
service hook
before: {
all: [],
find: [
hookBeforeFind,
search({
fields: ["label"],
deep: true
})
],
Model
const conversation = new Schema(
{
label: { type: String, required: true },
nodeId: { type: String, required: true },
details: { type: String },
url: { type: String },
creator: { type: String },
handle: { type: String },
date: { type: String },
From search bar add expression to search. E.g "the"
Add $regex to the whitelist option of the Mongoose service:
app.use('/messages', service({
Model,
whitelist: [ '$regex' ]
}));
try this
// regex to find records that start with letter any name , example "e"
Model.aggregate([
{
$match: {
field_name: {
$regex: "^" + searchName,
$options: "i"
}
}
}]).exec(function(err, result) {
if (err) { // handle here }
if (result) { // do something }
}

Sails.js + Waterline: Many-to-Many through association

I'm new to Sails.js (v0.10.5) and Waterline ORM. I have 3 tables in database: users (id, name), roles(id, alias) and join table users_roles(user_id, role_id). It's important not to change table names and field names in database. I want Policy entity to be a join entity between User and Role. Here is some mapping code:
//User.js
module.exports = {
tableName: 'users',
autoCreatedAt: false,
autoUpdatedAt: false,
attributes: {
id: {
type: 'integer',
required: true
},
name: {
type: 'string'
},
roles: {
collection: 'role',
via: 'users',
through: 'policy'
},
}
}
//Role.js
module.exports = {
tableName: "roles",
autoCreatedAt: false,
autoUpdatedAt: false,
attributes: {
id: {
type: 'integer',
required: true
},
alias: {
type: 'string',
required: true
},
users: {
collection: 'user',
via: 'roles',
through: 'policy'
}
}
}
//Policy.js
module.exports = {
tableName: "users_roles",
tables: ['users', 'roles'],
junctionTable: true,
autoCreatedAt: false,
autoUpdatedAt: false,
attributes: {
user: {
columnName: 'user',
type: 'integer',
foreignKey: true,
references: 'user',
on: 'id',
via: 'role',
groupBy: 'user'
},
roles: {
columnName: 'role',
type: 'integer',
foreignKey: true,
references: 'role',
on: 'id',
via: 'user',
groupBy: 'role'
}
}
}
But when I trying to access roles atribute in controller
User.findOne({id: 1}).populate('roles').exec(function(err, user) {
console.log(JSON.stringify(user.roles));
});
this returns
[]
And
User.findOne({id: 1}).populate('roles').exec(function(err, user) {
console.log(JSON.stringify(user));
});
returns
{"id":1,"name":"test", "roles":[]}
I checked twice that user, role and association between them exists in database. What is my mistake?
I have found way to solve this problem. It's not what I exactly want, but it works.
First: join entity:
//Policy.js
module.exports = {
tableName: "users_roles",
autoPK: false,
attributes: {
id: {
type: 'integer',
primaryKey: true,
autoIncrement: true,
},
user: {
columnName: 'user_id',
model: 'user'
},
role: {
columnName: 'role_id',
model: 'role'
}
},
//tricky method to get all users for specified role_id
//or to get all roles for specified user_id
get: function(id, modificator, cb) {
var fields = ['user', 'role'];
if (fields.indexOf(modificator) < 0) {
cb(new Error('No such modificator in Policy.get()'), null);
}
var inversedField = fields[(fields.indexOf(modificator) + 1) % 2];
var condition = {};
condition[inversedField] = id;
this.find(condition).populate(modificator).exec(function(err, policies) {
if (err) {
cb(err, null);
return;
}
var result = [];
policies.forEach(function(policy) {
result.push(policy[modificator]);
});
cb(null, result);
return;
});
}
}
As you see, I added ID field to this entity (and to db table users_roles too), so it's not the great solution.
//User.js
module.exports = {
tableName: 'users',
autoPK: false,
attributes: {
id: {
type: 'integer',
primaryKey: true,
autoIncrement: true,
unique: true,
},
name: {
type: 'string'
},
policies: {
collection: 'policy',
via: 'user'
}
}
}
And Role Entity:
//Role.js
module.exports = {
tableName: 'roles',
autoPK: false,
attributes: {
id: {
type: 'integer',
primaryKey: true,
autoIncrement: true,
},
alias: {
type: 'string',
required: true,
unique: true,
},
policies: {
collection: 'policy',
via: 'role'
}
}
}
That's how I get all roles for specified user_id:
...
id = req.session.me.id; //user_id here
Policy.get(id, 'role', function(err, roles) {
var isAdmin = false;
roles.forEach(function(role) {
isAdmin |= (role.id === 1);
});
if (isAdmin) {
next(null);
return;
} else {
return res.redirect('/login');
}
});
...
Maybe it'll be usefull for somebody =)

Creating sorted tree in DOJO 1.6?

I new to learn dojo and trying to learn by it using samples code.
Using dojo 1.6
With help of sample codes , I created a tree
now i want to apply sorting on root and also on child.
With the help of this sample code , i changed the code
Output is not sorted n but the root folder has changed their position and child is deleted.
Plz help me to resolve this.
My code :
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.tree.ForestStoreModel");
dojo.require("dijit.Tree");
var data = [ { id: 1, name: "answerTypeLabel", type:'scenario', children:[{_reference: 2}]},
{ id: 2, name: "acceptRequestLabel", type:'paragraph', data: "acceptRequestLabel"},
{ id: 3, name: "rejectRequestLabel", type:'scenario', children:[{_reference: 5},{_reference: 6}]},
{ id: 4, name: "MoreInformationLabel", type:'scenario', children:[{_reference: 7},{_reference: 8}]},
{ id: 5, name: "rejectRequestStatusLabel", type:'paragraph', data: "rejectRequestStatusLabel"},
{ id: 6, name: "rejectRequestNotCoveredLabel", type:'paragraph', data: "rejectRequestNotCoveredLabel" },
{ id: 7, name: "MoreInformationDocumentLabel", type:'paragraph', data: "MoreInformationDocumentLabel"},
{ id: 8, name: "MoreInformationDataLabel", type:'paragraph', data: "MoreInformationDataLabel"}
];
dojo.addOnLoad(function() {
var sortableStore = new dojo.data.ItemFileReadStore({
data: {
identifier: 'id',
label: 'name',
items: data
}
});
var model = new dijit.tree.ForestStoreModel({
rootLabel: 'Names',
store: new dojo.data.ItemFileWriteStore({
data: {
identifier: 'id',
items: [],
label: 'name'
}
}) // blank itemsstore
})
var tree = new dijit.Tree({
model: model,
updateItems: function(items) {
var self = this;
console.log('pre', this.model.root.children);
dojo.forEach(items, function(newItem) {
console.log('add', newItem);
try {
self.model.store.newItem({
id: sortableStore.getValue(newItem, 'id'),
name: sortableStore.getValue(newItem, 'name'),
type: sortableStore.getValue(newItem, 'type'),
data: sortableStore.getValue(newItem, 'data'),
});
} catch (e) {
console.log(e);
}
});
console.log('post', this.model.root.children);
console.log("children: ", this.rootNode.getChildren());
},
});
tree.placeAt(dojo.body());
sortableStore.fetch({
query: {
type:'scenario'
},
sort: [{
attribute: "name"}],
onComplete: function(items) {
console.log(items, 'sorted');
tree.updateItems(items);
}
})
});
Output :
The 'Names' origins from you setting 'rootLabel'.
Btw, fiddles have revisions and is simply a paste-bin like feature :)
You need to use the tree model pasteItem to insert referenced items (the 'children' property of each 'newItem').
Otherwise, there's another approach, if you get rid of the '_reference' structure of your data. See: http://jsfiddle.net/GHFdA/1/

How to inform a selectfield element from response of Ext.Ajax.request?

I need to inform a selectfield sencha element from callback of Ext.Ajax.request({})
I have a this code, for example,
Ext.Ajax.request({
url: '/express/EXPRESSVE00007_es.jsp',
timeout: 90000,
params: {
evento : action,
cookie: document.cookie,
NAME : Ext.getCmp("txtName").getValue(),
LAST : Ext.getCmp("txtLast").getValue(),
SEX : Ext.getCmp("txtSex").getValue()
},
success: function(r, o) {
var response = r.responseText
response = response.trim()
response = response.replace('\n', '').replace('\r', '')
var jsonResponse = Ext.decode(response)
Ext.Msg.alert(jsonResponse)
},
failure: function() {
Ext.Msg.show({
title: "Failure",
msg: "Error, failed response",
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.ERROR
})
}
})
and my selectfield,
{
xtype: 'selectfield',
id: 'selSex',
name: 'select',
label: '*Sex',
placeHolder: 'Select...',
displayField: 'desc',
hiddenName: 'second-select',
options: [
{desc: '', value: ''},
{desc: '', value: ''}
]
}
In this case, I need to inform "desc" and "value" field from callback Ext.Ajax.request, but I don't know. Please help me.
You can inform the selectfield from an Ext.Ajax.request by updating it's store.
You could declare a store to store all the field values and then on response from the request, you can shuffle the data store to which selectfield is binded.
E.g
{
xtype: 'selectfield',
store: sampleStore,
valueField:'value',
displayField:'desc',
}
and update the store values on Ext.Ajax.request's response like this,
Ext.StoreMgr.get('sampleStore').load();
You can do below
Test = Ext.regModel('Test', {
fields: [{
name: 'desc',
type: 'string'
}, {
name: 'value',
type: 'string'
}]
});
exStores = new Ext.data.Store({
model: 'Test',
autoLoad: false });
and select field
{
xtype: 'selectfield',
store: exStores,
id: 'selSex',
name: 'select',
label: '*Sex',
placeHolder: 'Select...',
valueField:'value',
displayField:'desc',
}
and ajax request
Ext.Ajax.request({
...
success: function(r, o) {
var response = r.responseText
response = response.trim()
response = response.replace('\n', '').replace('\r', '')
var jsonResponse = Ext.decode(response)
exStores.loadData(jsonResponse, false);
Ext.Msg.alert(jsonResponse)
},
...
})
Hope this help.