Full text search in loopback on User model via MondoDB connector - javascript

I want to search my User collection via full text search on both the firstName and lastName property.
I create my index like this:
//connect to connector
server.datasources.db.connector.connect(function (err, db) {
//create index on firstName and lastName
db.collection('User').createIndex(
{ firstName: "text", lastName: "text" },
function (err) {
if (!err) {
//run autoupdate on each model
Promise.each(server.models(), function (model) {
if (model.dataSource) {
var autoupdate = Promise.promisify(model.dataSource.autoupdate);
if (autoupdate) {
console.log("running autoupdate on model: " + model.modelName);
return autoupdate.call(model.dataSource, model.modelName);
}
}
});
}
else {
console.log(err);
}
});
});
But when i query the database for a search string i always get zero results via direct access:
var mongodb = models.User.getDataSource().connector.collection(models.User.modelName);
mongodb.find({ $text: { $search: "Test" } },
function (err, resp) {
resp.toArray(function (err, docs) {
//docs always empty
cb(null, docs);
});
});
Or i get every entry when i use the Angular client like:
User.find({ where: { '$text': { search: "Test" } } }).$promise.then(function (resp) {
console.log(resp)
});
What am i missing?

Related

How to update document field in mongodb?

I am new to Mongodb so below code i am trying to update document field string i have object recieved in post req.body now based on _id i want to update string field but it is not updating record with below implementation. How can i update record using _id ? Any better approach to update record in terms of async will be appreciated.
routes.js
var Diagram = require('./diagram');
router.post('/saveUpdateDiagram',function(req,res){
console.log(req.body._id);
Diagram.update(req.body);
});
diagram.js
var diagram = require('./diagram.model');
var mongoose = require('mongoose');
var Diagram = {
index: function(callback) {
diagram.find({}, function(err, result) {
if (!err) {
callback(result);
}
});
},
update: function(data) {
console.log('data in controller', data);
Diagram.update({ $set: { 'string' : data.string } });
}
}
module.exports = Diagram;
data.json
{
_id: "57fe42efc3590c7686bad563"
groups: Array[0]
owner: "sh587"
string: "test string should be updated"
text: "gcs_wf_dit.bpmn"
users: Array[1]
}
We know that JavaScript is case sensitive language you should use diagram.update not Diagram.update
use `diagram.update({ $set: { 'string' : data.string } });
diagram.js should be
diagram.js
var diagram = require('./diagram.model');
var mongoose = require('mongoose');
var Diagram = {
index: function(callback) {
diagram.find({}, function(err, result) {
if (!err) {
callback(result);
}
});
},
update: function(data) {
console.log('data in controller', data);
diagram.update({_id: data._id}, { $set: { 'string' : data.string } });
}
}
module.exports = Diagram;
Make sure you have "string" field in diagram model. as mongoose allow only those fields which are available in schema. If not then add
string: {type: String}
and then use
var diagram = require('./diagram.model');
var mongoose = require('mongoose');
var Diagram = {
index: function(callback) {
diagram.find({}, function(err, result) {
if (!err) {
callback(result);
}
});
},
update: function(data) {
diagram.update({_id: data._id}, { $set: { 'string' : data.string } });
}
}
module.exports = Diagram;

Sails.js: Inserting one-to-many associated models to MongoDB

I am trying to take advantage of the Waterline ORM in Sails.js to build an example app that has a model called 'Category'. Because a category can have multiple sub categories, I have the following one-to-many association for this model:
module.exports = {
adapter: 'mongo',
// adapter: 'someMysqlServer',
attributes: {
categoryTitle: {
type: 'string',
required: true
},
parentCat: {
model: 'category'
},
subCategories: {
collection: 'category',
via: 'parentCat'
},
articles: {
collection: 'article',
via: 'category',
required: false
}
}
};
In the CategoryController.js, I have the create method that first tries to see if the new category has a parent category assigned to it; however, I feel the code is quite messy, and the parentCat in Mongodb is always empty even if I tried to assign a parent category in the form submission. So I am wondering if this is the right way to do it:
create: function(req, res, next) {
var params = req.allParams();
// set parent category if exists
if (params.parentCat) {
Category.findOne({categoryTitle : params.parentCat})
.exec(function(err, category) {
if (err) {
return false; //not found
} else {
params.parentCat = category.id; //found the parent category
console.log('parent cat id is: ', category.id);
}
});
}
Category.create(params, function(err, newCategory) {
if (err) {
return next(err);
} else {
console.log('new category created');
}
console.log('successfully added the category: ' + newCategory.categoryTitle)
res.redirect('/category');
}); // create the category
}
The issue of your code is the callback.
I created a new version of code with the async feature (which is already in your sails app), hope it will help you.
create: function(req, res, next) {
var params = req.allParams();
async.waterfall([
function(callback) {
// set parent category if exists
if (params.parentCat) {
Category.findOne({
categoryTitle: params.parentCat
})
.exec(function(err, category) {
if (err) {
return false; //not found
}
params.parentCat = category.id; //found the parent category
console.log('parent cat id is: ', category.id);
callback(null, params);
});
} else {
callback(null, params);
}
},
function(params, callback) {
Category.create(params, function(err, newCategory) {
if (err) {
return next(err);
}
console.log('successfully added the category: ' + newCategory.categoryTitle);
callback(null, newCategory);
}); // create the category
}
], function(err, result) {
console.dir(result);
res.redirect('/category');
});
}

How do i Find all registers of one only column in sails.js

How do i Find all registers of one only column in sails
my model is:
models/Blog.js
module.exports = {
schema: true,
attributes: {
title:'string',
content:{
type:'string',
required: true
}
}
};
my controller:
controllers/BlogController.js
module.exports = {
index: function (req, res) {
Blog.find()
.exec(function (err, content) {
if (err) {
res.send(400);
} else {
res.view({OnlyContent:content}); // Only view all Content ?
}
});
},
_config: {}
};
To only send the data of content to your client, you need to loop through the returned array of blogs and filter out the content.
index: function (req, res) {
Blog.find().exec(function (err, allBlogs) {
if (err) {
res.send(400);
} else {
var allContent = [];
allBlogs.forEach(function (blog) {
allContent.push(blog.content);
})
res.view({
OnlyContent: allContent
});
}
});
}

object being returned as undefined

RouteHandler
function getProfile(req, res) {
var graphs = dataSaver.getGraphs(req.user.email)
console.log(graphs)
res.render('profile', {
title: 'EZgraph | User Home',
userGraphs: graphs
})
}
Db code
function getGraphs(username) {
model.findOne({
email: username
},
function(err, user) {
if (err) {
console.log('err')
}
if (!user) {
console.log('no user found!')
} else {
var graphs = user.savedGraphs
console.log(graphs)
return graphs
}
}
)
}
using the above two methods I'm trying to pass data read from the DB to a jade view. The problem is that within the scope of the 2nd method that reads from the db, the object is read fine, the console.log call shows me that. Once I return this object though and return to the scope of the route handler, the variable that should be equal to the object no prints as undefined. How do I fix this?
EDIT
In repsonse to the comments I tried the following, it isn't pretty at all but I run into the same problem.
Handler + helper
function getProfile(req, res) {
var graphs = dataSaver.getGraphs(req.user.email, readSuccess)
console.log(graphs);
res.render('profile', {
title: 'EZgraph | User Home',
userGraphs: graphs
})
}
function readSuccess(data) {
return data
}
db code
function getGraphs(username, callback) {
model.findOne({
email: username
},
function(err, user) {
if (err) {
console.log('err')
}
if (!user) {
console.log('no user found!')
} else {
callback(user.savedGraphs)
}
}
)
}

nodejs prototype and nested callbacks with mysql

I have two problems with the code below. It is the beginning of a node.js module for registering users that are stored in a mysql database.
The first problem is that in the callback from the first query the variable this.connection is undefined. The second problem is that the variable user is also undefined in the same callback. Hence the code crashes on the following line:
this.connection.query('INSERT INTO users{{values values}}', {
values: {
user_name: user.username,
user_email: user.email,
user_password: user.password
}
})
Please let me know how to solve this in a propper way.
Many thanks!
Full code is below:
module.exports = usermodel;
//connection is a mysql-wrapper connection
function usermodel(connection)
{
this.connection = connection;
}
playermodel.prototype = {
registerByEmail: function (user, callback) {
//check firts if the user already exists
this.connection.query('SELECT user_id FROM users {{where data}}', {
data: {
user_email: user.email
}
},
function (err, result) {
if (err) {
...
} else if (result.length > 0) {
...
} else {
// this.connection is undefined ????????????
this.connection.query('INSERT INTO users {{values values}}', {
values: {
user_name: user.username,
user_email: user.email,
user_password: user.password
}
}),
function (err, result) {
...
}
}
});
}
}
this.connection is undefined because this.connection is on the instance of playermodel the callback function passed to the first query does not know about the context of the playermodel instance.
user should be defined though. You can get around the this.connection being undefined by either binding the function or setting a reference to this in a variable the the callback will have access to.
//Bind
playermodel.prototype = {
registerByEmail: function (user, callback) {
//check firts if the user already exists
this.connection.query('SELECT user_id FROM users {{where data}}', {
data: {
user_email: user.email
}
},
function (err, result) {
if (err) {
...
} else if (result.length > 0) {
...
} else {
// this.connection is undefined ????????????
this.connection.query('INSERT INTO users {{values values}}', {
values: {
user_name: user.username,
user_email: user.email,
user_password: user.password
}
}),
function (err, result) {
...
}
}
//HERE
}.bind(this));
}
}
or
//me reference to this
playermodel.prototype = {
registerByEmail: function (user, callback) {
//HERE
var me = this;
//check firts if the user already exists
this.connection.query('SELECT user_id FROM users {{where data}}', {
data: {
user_email: user.email
}
},
function (err, result) {
if (err) {
...
} else if (result.length > 0) {
...
} else {
//HERE
me.connection.query('INSERT INTO users {{values values}}', {
values: {
user_name: user.username,
user_email: user.email,
user_password: user.password
}
}),
function (err, result) {
...
}
}
});
}
}

Categories