community. I am trying to implement a live search using the autocomplete library but every try is unsuccessful. I get every time a 500 server error. Every assistant is appreciated because I am new in coding.
I have a simple model for an article with title and body and I would like to show suggestions when the user search for an article
model/article.js
// Method to construct the json result set
module.exports.buildResultSet=function(docs) {
var result = [];
for(var object in docs){
result.push(docs[object]);
}
return result;
}
routes/article.js
router.get('/search', function(req, res){
encyclopediaModel.getMyArticlesByName(theRequester, function (pError, pFoundedArticles) {
if (!pError) {
// Method to construct the json result set
var result = encyclopediaModel.buildResultSet(pFoundedArticles);
res.json(result);
} else {
return res.json(JSON.stringify(pError), {
'Content-Type': 'application/json'
}, 404);
}
},req.query.title)
});
//Ajax call
$("#search-query").autocomplete({
source: function (request, response) {
$.ajax({
url: "/encyclopedia/search",
type: "GET",
data: request, // request is the value of search input
success: function (data) {
response( data );
console.log('success', data);
}
});
},
// The minimum number of characters a user must type before a search is performed.
minLength: 3,
// set an onFocus event to show the result on input field when result is focused
focus: function (event, ui) {
this.value = ui.item.label;
// Prevent other event from not being execute
event.preventDefault();
},
select: function (event, ui) {
}
});
<input id="search-query" type="text" placeholder="Articles...">
module.exports.getMyArticlesByName = function (requester, callback, pTitle){
var regex = new RegExp(pTitle["term"], 'i');
article.find({title: regex}, { 'title': 1 }).sort({"updated_at":-1}).sort({"created_at":-1}).limit(20).exec(callback);
}
Related
so i wrote this function to check weather the login given exists already in the odoo database, but it always returns undefined, my guess is that it returns undefined because the return line is inside the calling method,
i tried to use it as an async function but it didn't work either, i need to know how can i make the return line refrences to the global function scope and not just the calling method.(i need the calling method to get the full list of users from the odoo database). Any suggestions ??
`
function user_exist(email){
odoo.connect(function (err) {
if (err) { return console.log(err); }
console.log('Connected to Odoo server.');
var inParams = [];
inParams.push([['active', '=', true]]);
var params = [];
params.push(inParams);
// 4- Read
odoo.execute_kw('res.users', 'search', params, function (err, value) {
if (err) { return console.log(err); }
var inParams = [];
inParams.push(value); //ids
inParams.push(['login']);
var params = [];
params.push(inParams);
odoo.execute_kw('res.users', 'read', params, function (err2, value) {
if (err2) { return console.log(err2); }
for (let i = 0; i < value.length; i++) {
if (email == value[i].login){
return "User exist"
}
}
return "user doesn't exist"
});
});
});
}
`
if you are making your api you need to learn how to use postman, and in this solution we are using axios:
var axios = require('axios');
let data = JSON.stringify({
"jsonrpc": "2.0",
"method":"call",
"params": {
"service":"object",
"method":"execute",
//arg1 : your database name must be "string"
//arg2 : id of the user admin must be "int" ex:1 or 3 or 66
//arg3 : password of the user admin must be "string"
// admin:admin do like this 2:"admin"
//arg4 : object or model name ex:"res.users"
//arg5 : orm methods ex:"search,search_read..."
//"args":["arg1",'arg2',"arg3","arg4","arg5"]}
"args":["app",2,"admin","res.users","search_read",[],[]]
}
});
let config = {
method: 'get',
url: 'http://localhost:8069/jsonrpc',
headers: {'Content-Type': 'application/json'},
data : data
};
axios(config).then(response => {handleResult(response)})
function handleResult(data) {
// if you want you can remove result
console.log(JSON.stringify(data.data.result));
}
i hope this will be help you
I want to have my list sorted alphabetically by the child name 'name'. Currently this is the Server file I am using to render the page:
app.get('/testpage', function (request, response) {
var testDBref = database.ref('testdb')
testDBref.once('value', function (snapshot) {
var result = snapshot.val()
if (!result) {
result = {}
};
response.render('TestPage.ejs', {
items: result,
pageTitle: "My Lists"
});
});
});
However, when I do the following:
app.get('/testpage2', function (request, response) {
var testDBref2 = database.ref('testdb').orderByChild('name')
testDBref2 .once('value', function (snapshot) {
snapshot.forEach(function(child){
console.log(child.val()) // NOW THE CHILDREN PRINT IN ORDER
var result = snapshot.child('name').snapshot.key
response.render('testpage2.ejs', {
items: result,
pageTitle: "My Lists"
});
});
});
});
It errors out saying: cannot set headers after they are sent to the client, req.next is not a function.
When I just have it console to the log:
app.get('/testpage2', function (request, response) {
var testDBref2 = database.ref('testdb').orderByChild('name')
testDBref2 .once('value', function (snapshot) {
snapshot.forEach(function(child){
console.log(child.val())
});
});
});
It is sorted alphabetically in json (but of course it doesn't display in the web page). I'm new to the nosql db's so any assistance would be appreciated :)
If you want the keys in the order of the name property, you will have to use the forEach operator. That's because the order of keys in a JSON object is undefined, but most JSON processors will return them alphabetically.
But as you also found, you can only call response.render once, so if you want to return multiple child nodes, you'll have to render them outside of the forEach loop.
The solution is to convert the child nodes to an array, and (if needed) put the key of each child node in the object in the array. For example:
app.get('/testpage2', function (request, response) {
var testDBref2 = database.ref('testdb').orderByChild('name')
testDBref2 .once('value', function (snapshot) {
var result = [];
snapshot.forEach(function(child){
result.push({ key: child.key, name: child.child('name').val() });
});
response.render('testpage2.ejs', {
items: result,
pageTitle: "My Lists"
});
});
});
I am new to Apostrophe and trying to create a contact us form with file attachment in Apostrophe by following the tutorial.
https://apostrophecms.org/docs/tutorials/intermediate/forms.html
I have also created the attachment field in my index.js and it works fine from the admin panel.
Now, I am trying to create my own html for the form with file submission.
// in lib/modules/contact-form-widgets/public/js/always.js
apos.define('contact-form-widgets', {
extend: 'apostrophe-widgets',
construct: function(self, options) {
self.play = function($widget, data, options) {
var $form = $widget.find('[data-contact-form]');
var schema = self.options.submitSchema;
var piece = _.cloneDeep(self.options.piece);
return apos.schemas.populate($form, self.schema, self.piece, function(err) {
if (err) {
alert('A problem occurred setting up the contact form.');
return;
}
enableSubmit();
});
function enableSubmit() {
$form.on('submit', function() {
submit();
//I can access file here
// console.log($form.find('file'))
return false;
});
}
function submit() {
return async.series([
convert,
submitToServer
], function(err) {
if (err) {
alert('Something was not right. Please review your submission.');
} else {
// Replace the form with its formerly hidden thank you message
$form.replaceWith($form.find('[data-thank-you]'));
}
});
function convert(callback) {
return apos.schemas.convert($form, schema, piece, callback);
}
function submitToServer(callback) {
return self.api('submit', piece, function(data) {
alert("I AM AT SUBMIT API ")
if (data.status === 'ok') {
// All is well
return callback(null);
}
// API-level error
return callback('error');
}, function(err) {
// Transport-level error
alert("I AM HERE AT API ERROR")
return callback(err);
});
}
}
};
}
});
//and my widget.html is
<div class="form-group">
<input name="custom-file" type="file">
</div>
When I run this I get following errors
user.js:310 Uncaught TypeError: Cannot read property 'serialize' of undefined
at Object.self.getArea (user.js:310)
at Object.self.getSingleton (user.js:303)
at Object.convert (user.js:686)
at user.js:164
at async.js:181
at iterate (async.js:262)
at async.js:274
at async.js:44
at setImmediate.js:27
at runIfPresent (setImmediate.js:46)
My question is, how do I handle file submission? Is there any better approach for this?
This is much easier to do using the apostrophe-pieces-submit-widgets module, which allows you to define a schema for what the user can submit. You can include a field of type attachment in that, and this is demonstrated in the README.
I am trying to create an eventlog type of field on mongodb records where I can store a list of activity. The first time I run the function, it appends to the array correctly but subsequent calls overwrite the last entry instead of appending. If I restart the server or refresh the page in the browser, it will append once again then repeat the same behavior.
I'm learning node and javascript so I'm sure it's some mistake I've made but I don't seem able to figure it out.
Javascript on the client is a tabulator event.
cellEdited:function(cell){
//cell - cell component
const oldValue = cell.cell.oldValue;
const newValue = cell.cell.value;
const title = cell.cell.column.definition.title;
var report = cell.cell.row.data;
report.event = `Updated ${title} from ${oldValue} to ${newValue}`;
$.ajax({
type: 'POST',
url: '/api/update',
data: report,
dataType: 'json'
});
}
The route that its calling on the server:
app.post('/api/update', isAuthenticated, function(req, res) {
var report = req.body;
var reason = '';
if (typeof report.event !== 'undefined') {
reason = report.event;
delete report.event;
} else {
reason = 'Report updated';
}
db.DamageReport.findOneAndUpdate({ _id: report._id}, report, function (err, doc) {
if (err) {
console.log('Err updating report ', err);
return res.send(500, { error: err});
}
/*
* Write eventlog
*/
var event = {"date": new Date(), "user": req.user.email, "event": reason };
appendLog(doc._id, event);
return res.json(doc);
});
});
The appendLog function:
function appendLog(id, entry) {
/*
* entry format:
* date: Date
* user: String
* event: String
*/
if (typeof(entry.date) !== 'object') {
entry.date = new Date();
}
db.DamageReport.findByIdAndUpdate(id, {$push: {eventLog: entry}}, function(err, result) {
if (err) {
return console.log('Error writing eventLog: ', err);
}
return(result);
});
}
It wouldn't append more than one because the previous save contained the Eventlog array in it's original form so every time it saved, it set it back to the original array and then appended the last update.
I'm developing a simple app with Node/Hapi/Mongodb, but running into a strange issue. Below is the route that handles adding/updating scores; when I send some data to this endpoint through Insomnia/Postman it works as expected. However, when this POST is coming from a different app I'm getting strange results; the value is always null for every field (again this only happens when the POST is coming from another site, but I've logged out the request payload and can see that the data is correct, just gets set to null when assigning to an object, or trying to use it a query)
server.route({
method: 'POST',
path: '/update-score',
handler: (request, h) => {
var scores = db.collection('scores');
var updateScore = new Promise((resp, rej) => {
console.log('payload ', request.payload);
scores.findOneAndUpdate({customerID: request.payload.customerID}, {$set: {customerID: request.payload.customerID, customerName: request.payload.customerName, highScore: request.payload.highScore}}, {upsert: true}, (err, res) => {
if (err) {
return rej(err);
}
else {
return resp(res);
}
})
});
return updateScore;
}
});
The console logs out the request payload correctly, but its null/undefined when the query tries to use it. I have also tried creating two objects, outside the mongo method call (like below), and after console logging these pre-defined objects out the value was null there as well; even though I can console.log the request.payload after defining these objects and the data is good.
server.route({
method: 'POST',
path: '/update-score',
handler: (request, h) => {
var scores = db.collection('scores');
var queryObj = {
customerID: request.payload.customerID
};
var updateObj = {
$set: {
customerName: request.payload.customerName,
highScore: request.payload.highScore
}
}
var updateScore = new Promise((resp, rej) => {
console.log('again ', request.payload);
scores.findOneAndUpdate(queryObj, updateObj, {upsert: true}, (err, res) => {
if (err) {
return rej(err);
}
else {
return resp(res);
}
})
});
return updateScore;
}
});
Logging the queryObj and valueObj would show the values are all null, even though I can log the request.payload and see the data correctly. Why can't I use the request.payload values anywhere?
Long story short, Insomnia/Postman sends an object as the POST body, but I was JSON encoding the POST from the app; just needed to parse that on the server!