I want to display some query mongoose result data using Angular on an html page - node.js

I have a little problem, I want to display some mongoose query result data using Angular on on an html page.
I don't know how to send data to the angular $scope.
app.js:
User.find({ Code: doc.Code}, function (err, data){
var users = [];
var userswithsamecode = '';
data.forEach(function(d){
console.log(d.nom + " " + d.prenom);
users.push(d);
userswithsamecode += "<li>" + d.nom +" "+ d.prenom + '</li><br>';
How can I send this result to the angular $scope,
collegues.html
<html data-ng-app="demo">
<div data-ng-controller="simple">
Name:
<br/>
<input type="text" data-ng-model="name" />
<br/>
<ul>
<li data-ng-repeat="collegue in collegues |filter:name">{{}} </li>
</ul>
</div>
<script src="angular.min.js"></script>
<script>
var demo=angular.module('demo', []);
function simple($scope){
$scope.collegues=
];}
demo.controller('simple', simple);
</script>'
Thanks for your help!

First you need to create a model for mongo. An example
var Example = mongoose.model('ExampleCollection'{
name:String,
description: String
});
//posting to a mongodb
var example = new Example (
app.post("/add-something-to-mongo", function(req, res) {
name: req.body.name,
description: req.body.description
});
listing.save(function(err) {
if(err) {
console.log("Error! ", err);
}else
{
console.log("Saved!"
};
});
});
});
The angular code would look something like this.
var app = this;
var url = "heroku_url or localhost url";
app.save = function(Example) {
// create a new object
var newExample = {
"name": $scope.name
"description": $scope.description
};
$http.post(url + "/routefromserver", newExample).success(function() {
console.log("posting");
})
};
And lastly the HTML
<input id="name" type="text" ng-model="name" />
<input id="city" type="text" ng-model="description"/>
<button ng-click="app.save()">Save Me</button>

Related

How to update a widget when modifying model data in Odoo

I'm showing the reported hours of a User on the Odoo navbar but I have to F5 if I want to update the data.
It's possible to update the reported hours when someone modifies the model data that contain this information?
My javascript code
odoo.define('L6Odoo13_systray_reported_hours.systray_reported_hours', function (require) {
"use strict";
var Widget = require('web.Widget');
var SystrayMenu = require('web.SystrayMenu');
var field_utils = require('web.field_utils');
var core = require('web.core');
var session = require('web.session');
var ReportedHours = Widget.extend({
template: 'ReportedHours',
init: function() {
this.reported_hours = 0
this._super.apply(this, arguments);
},
events: {
'onchange account.analytic.line': 'willStart',
},
willStart: function(){
var self = this;
var def = this._rpc({
model: 'account.analytic.line',
method: 'search_read',
args: [[['user_id', '=', this.getSession().uid]], ['name', 'unit_amount', 'date']],
})
.then(function (res) {
var today = new Date();
var hoy = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate()
if (res.length) {
var total = 0.0
res.forEach(function(elem){
if (elem.date === hoy){
total += elem.unit_amount
}
})
self.reported_hours = field_utils.format.float_time(total);
}
});
return Promise.all([def, this._super.apply(this, arguments)]);
},
})
ReportedHours.prototype.sequence = 90;
SystrayMenu.Items.push(ReportedHours);
return {
ReportedHours: ReportedHours,
};
});
My xml code
<?xml version="1.0" encoding="UTF-8" ?>
<templates>
<t t-name="ReportedHours">
<li class="o_mail_systray_item" style="margin-top: 13px;">
<div>
<span t-esc="widget.reported_hours"/>
</div>
</li>
</t>
</templates>
Of course I know that the code in 'events:' is incorrect, but is what I'm looking for.
I want to update the 'self.reported_hours' when someone modifies the 'account.analytic.line' data.

How to structure the NodeJs code

I am new to the NodeJs. I have created a simple application using socket.io. I know that I can use ExpressJs framework but I am not getting overall idea as to how to separate the code and divide them into multiple pages so that debugging and maintenance is easily.
I am not understanding how to structure the code and where to write the socket.io code or any other NodeJs code in general.
Should I create new folder and files? If yes then how?
My code: app.js
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var ent = require('ent');
var fs = require('fs');
var cntActiveProductSupport = 0;
var cntActiveCustomer = 0;
var support_socket_id = '';
app.get('/',function (req, res) {
res.sendFile(__dirname+'/index.html');
});
app.get('/product_support',function (req, res) {
res.sendFile(__dirname+'/admin.html');
});
io.sockets.on('connection',function(socket,username){
//Each Socket in Socket.IO is identified by a random, unguessable, unique identifier Socket#id
console.log(socket.id);
//total number of connections
console.log(io.engine.clientsCount);
socket.on('support_connected',function(username){
username = ent.encode(username);
socket.username = username;
socket.broadcast.emit('support_connected',username);
//get socket id of all connected sockets
Object.keys(io.sockets.sockets).forEach(function(id) {
console.log("ID:",id) // socketId
});
cntActiveProductSupport++;
support_socket_id = socket.id;
});
socket.on('new_client',function(username){
var client_socket_id = socket.id;
username = ent.encode(username);
socket.username = username;
socket.broadcast.emit('new_client',{ username: username, socket_id: socket.id, support_socket_id: support_socket_id });
socket.to(client_socket_id).emit('client_connected',{ username: username, support_socket_id: support_socket_id });
cntActiveCustomer++;
});
socket.on('message',function(data){
//socket.disconnect(true); use this if you want to disconnect client from server
//client which sent the message
var client_socket_id = socket.id;
var message = ent.encode(data.message);
// sending to individual socketid (private message)
//socket.to(socketId).emit('hey', 'I just met you');
socket.to(support_socket_id).emit('message', {username: socket.username,message:message, client_socket_id: client_socket_id});
});
socket.on('support_messaging',function(data){
message = ent.encode(data.message);
var customer_socket_id = data.customer_socket_id;
//socket.broadcast.emit('message', {username: socket.username,message:message});
// sending to individual socketid (private message)
socket.broadcast.to(customer_socket_id).emit('message', {username: socket.username,message:message});
//socket.to(socketId).emit('hey', 'I just met you');
//It's the same command as for rooms, that's because:
//"For your convenience, each socket automatically joins a room identified by this id."
});
socket.on('typing',function(username){
socket.broadcast.emit('typing', username);
});
socket.on('stopped-typing',function(){
socket.broadcast.emit('stopped-typing');
});
});
server.listen(8080);
My code: index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Real-time Super Chat!</title>
<style>
#zone_chat strong {
color: white;
background-color: black;
padding: 2px;
}
#writeup {
font-size:9px;
color: gray;
margin: 5px 0px;
}
</style>
</head>
<body>
<h4>Real-time Super Chat!</h4>
<form action="/" method="post" id="chat_form" autocomplete="off">
<input type="text" name="message" id="message" placeholder="Your message..." size="50" />
<input type="submit" id="send_message" value="Send" />
<input type="hidden" id="support_socket_id" value=""/>
<div id="writeup"></div>
</form>
<section id="chat_zone">
</section>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
// Connecting to socket.io
var socket = io.connect('http://localhost:8080');
var socketConnected = false;
// The username is requested, sent to the server and displayed in the title
var username = prompt('What\'s your username?');
//var username = 'Deepak';
socket.emit('new_client', username);
document.title = username + ' - ' + document.title;
socket.on('connect', function() {
socketConnected = true;
console.log('Connected! ID: ' + socket.id);
});
socket.on('client_connected', function(data){
$('#support_socket_id').val(data.support_socket_id);
});
socket.on('disconnect', function() {
socketConnected = false;
console.log('Disconnected!');
});
// When a message is received it's inserted in the page
socket.on('message', function(data) {
insertMessage(data.username, data.message)
});
// When a new client connects, the information is displayed
// socket.on('new_client', function(username) {
// $('#chat_zone').prepend('<p><em>' + username + ' has joined the chat!</em></p>');
// });
socket.on('typing',function(username){
$('#writeup').html(username + ' is typing...');
});
socket.on('stopped-typing',function(){
$('#writeup').html('');
});
$(document).ready(function () {
$('#message').on('focus',function(){
socket.emit('typing',username);
});
$('#message').on('blur',function(){
socket.emit('stopped-typing',username);
});
// When the form is sent, the message is sent and displayed on the page
$('#chat_form').submit(function () {
var message = $('#message').val();
var support_socket_id = $('#support_socket_id').val();
socket.emit('message', { message:message, support_socket_id:support_socket_id }); // Sends the message to the others
insertMessage(username, message); // Also displays the message on our page
$('#message').val('').focus(); // Empties the chat form and puts the focus back on it
return false; // Blocks 'classic' sending of the form
});
});
// Adds a message to the page
function insertMessage(username, message) {
$('#chat_zone').prepend('<p><strong>' + username + '</strong> ' + message + '</p>');
}
</script>
</body>
</html>
You should create node modules in order to maintain the code structure. For example create routes folder and put all the route in there and separate them like users.js is a route file to cater routing related to user. As you are using socket.io you can create a separate module for socket.io functions and use them in your routes.
This link might help you: https://nodejs.org/api/modules.html
I hope it helps.
App Structure: routes, enter image description here

Why do I need to refresh the page to get the newly-updated data?

I was making an application including a comment function with "likes" and "dislikes" just like Facebook. But I find when users click the button of "like" or "dislike", everything goes well --- the database has been updated and the new data has been rendered back to previous webpage, except users need to refresh the page manually to get the new webpage with newly-updated data. Here are my files (I just take the codes of "like" function as example, the codes of "dislike" function is the same):
JS codes:
$("#scrollit").on("click", ".fa-thumbs-up", function(){
var numberOfLikes = Number($(this).next().html());
var numberOfDislikes = Number($(this).next().next().next().html());
numberOfLikes = numberOfLikes + 1;
var Text = $(this).next().next().next().next().next().html();
console.log(Text);
$.ajax({
method: "POST",
url: "/searchresult/comments/likes",
data: {text:Text, likes: numberOfLikes, dislikes: numberOfDislikes}
});
});
Node.js codes:
app.post("/searchresult/comments/likes", function(req, res) {
var likes = req.body.likes;
var Text = req.body.text;
new Promise(function(resolve, reject) {
comments.update({text: Text}, {$set: {likes: likes}}, function(err){
if (err) {
console.log(err);
} else {
console.log("Likes update successfully!");
resolve(comments);
}
});
}).then(function(r){
console.log("DONE!");
res.redirect("/searchresult");
});
});
app.get("/searchresult", function(req, res){
var EnglishofWord = EnglishofWords[EnglishofWords.length - 1];
grewords.findOne({English: EnglishofWord}).populate("Comments").exec(function(err, allgrewords){
if (err) {
console.log(err);
} else {
console.log(allgrewords);
if (allgrewords == null || allgrewords.length < 1 || allgrewords == undefined ) {
console.log("We don't have this word in dictionary!");
res.render("errorpage");
} else {
res.render("searchresult", {greword:allgrewords});
}
}
});
});
ejs codes:
<% greword.Comments.forEach(function(comment){ %>
<strong><p class="author"><%= comment.author %></p></strong>
<i class="far fa-thumbs-up"></i><span class="likes"><%= comment.likes %></span>
<i class="far fa-thumbs-down"></i><span class="dislikes"><%= comment.dislikes%></span>
<span class="pull-right">10 days ago</span>
<p><%= comment.text %></p>
<% }) %>
Could anybody help me to figure it out? ---- Why doesn't the webpage refresh itself automatically? Thanks so much! :P
//************************************************ Update! ***************************************************//
Thanks a lot to t3__rry, his/her suggestion was enlightening! Now I have made it work properly.

HTML5 audio not playing with Handlebars templated src attribute

I'm trying to play mp3's that I am streaming out of a Mongo GridFSBucket. The root of my issue is that I set the src attribute of my audio tag with my handlebars template to the URL that my stream should be headed to but the player is unresponsive.
If I don't feed this URL to my the audio tag and I remove the handlebars code, my browser (Chrome) creates a video tag that blacks out the window and superimposes HTML media player controls in the center and plays the track without issue.
How should I specify to the player that whatever it is streaming to the video tag it is creating should instead go to the audio player?
list.handlebars
<script src="../index.js" ></script>
<title>CRATE</title>
</head>
<body>
<div>tracks displayed below</div>
<div>{{userNameId}}'s Tracks</div>
{{#each tracks}}
<div class="row">
<div class="col-md-12">
<form id="trackSelection" method="GET" action="/play">
<input type="hidden" name="bytes" value="{{length}}">
<button class="playButton" type="submit" name="id" value=" .
{{_id}}">{{filename}}</button>
</form>
</div>
</div>
{{/each}}
<audio id="playback" src="{{sourceUrl}}" type="audio/mpeg" controls>
</audio>
</body>
</html>
index.js
app.get('/play', urlEditor, function(req, res, next) {
var db = req.db // => Db object
var size = sanitizer.escape(req.query.bytes);
var sanitizedTrackId = sanitizer.escape(req.query.id);
var username = 'ross';
var protocol = req.protocol;
var originalUrl = req.originalUrl;
// var sourceUrl = protocol + '://' + hosted + originalUrl;
var sourceUrl = protocol + '://' + req.get('host') + originalUrl;
console.log("sourceUrl", sourceUrl)
console.log("type", typeof sourceUrl)
if (username) {
const collection = db.collection(username + ".files");
var userNameId = collection.s.name;
console.log(userNameId);
const tracks = new Promise(function(resolve, reject) {
resolve(collection.find({}).toArray(function(err, tracks) {
assert.equal(err, null);
// return tracks;
finishPage(tracks);
}))
})
} else {
console.log('waiting')
}
function finishPage(tracks) {
try {
console.log("SID", sanitizedTrackId);
var trackID = new ObjectID(sanitizedTrackId);
} catch (err) {
return res.status(400).json({ message: "Invalid trackID in URL parameter. Must be a single String of 12 bytes or a string of 24 hex characters" });
}
let playEngine = new mongo.GridFSBucket(db, {
bucketName: username
});
var downloadStream = playEngine.openDownloadStream(trackID);
downloadStream.pipe(res);
console.log('success');
console.log("___________________");
var head = {
'Accept-Ranges': 'bytes',
'Content-Length': size,
'Content-Type': 'audio/mp3',
}
// res.render("list");
// res.set({ 'content-type': 'audio/mp3', 'accept-ranges': 'bytes', 'content-length': size }).render("list", { tracks: tracks, userNameId: userNameId, sourceUrl: sourceUrl });
res.status(206, head).render("list", { tracks: tracks, userNameId: userNameId, sourceUrl: sourceUrl });
}

Cannot connect mongodb and socket.io using node

I'm following this tutorial to make a basic socket.io chatroom connected to mongodb. Here is the code:
const mongo = require('mongodb').MongoClient;
const client = require('socket.io').listen(3000).sockets;
// Connect to mongo
mongo.connect('mongodb://127.0.0.1/mongochat', function(err, db){
if(err){
throw err;
}
console.log('MongoDB connected...');
// Connect to Socket.io
client.on('connection', function(socket){
let chat = db.collection('chats');
// Create function to send status
sendStatus = function(s){
socket.emit('status', s);
}
// Get chats from mongo collection
chat.find().limit(100).sort({_id:1}).toArray(function(err, res){
if(err){
throw err;
}
// Emit the messages
socket.emit('output', res);
});
// Handle input events
socket.on('input', function(data){
let name = data.name;
let message = data.message;
// Check for name and message
if(name == '' || message == ''){
// Send error status
sendStatus('Please enter a name and message');
} else {
// Insert message
chat.insert({name: name, message: message}, function(){
client.emit('output', [data]);
// Send status object
sendStatus({
message: 'Message sent',
clear: true
});
});
}
});
// Handle clear
socket.on('clear', function(data){
// Remove all chats from collection
chat.remove({}, function(){
// Emit cleared
socket.emit('cleared');
});
});
});
});
The code runs and I get
(node:31737) DeprecationWarning: current URL string parser is
deprecated, and will be removed in a future version. To use the new
parser, pass option { useNewUrlParser: true } to MongoClient.connect.
MongoDB connected...
But when I try to get the html page in browser I get This 127.0.0.1 page can’t be found instead.
Here is the index.html page on the same folder as server.js that is supposed to be rendered but it does not:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<title>MongoChat</title>
<style>
#messages{height:300px;}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3 col-sm-12">
<h1 class="text-center">
MongoChat
<button id="clear" class="btn btn-danger">Clear</button>
</h1>
<div id="status"></div>
<div id="chat">
<input type="text" id="username" class="form-control" placeholder="Enter name...">
<br>
<div class="card">
<div id="messages" class="card-block">
</div>
</div>
<br>
<textarea id="textarea" class="form-control" placeholder="Enter message..."></textarea>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script>
(function(){
var element = function(id){
return document.getElementById(id);
}
// Get Elements
var status = element('status');
var messages = element('messages');
var textarea = element('textarea');
var username = element('username');
var clearBtn = element('clear');
// Set default status
var statusDefault = status.textContent;
var setStatus = function(s){
// Set status
status.textContent = s;
if(s !== statusDefault){
var delay = setTimeout(function(){
setStatus(statusDefault);
}, 4000);
}
}
// Connect to socket.io
var socket = io.connect('http://127.0.0.1:4000');
// Check for connection
if(socket !== undefined){
console.log('Connected to socket...');
// Handle Output
socket.on('output', function(data){
//console.log(data);
if(data.length){
for(var x = 0;x < data.length;x++){
// Build out message div
var message = document.createElement('div');
message.setAttribute('class', 'chat-message');
message.textContent = data[x].name+": "+data[x].message;
messages.appendChild(message);
messages.insertBefore(message, messages.firstChild);
}
}
});
// Get Status From Server
socket.on('status', function(data){
// get message status
setStatus((typeof data === 'object')? data.message : data);
// If status is clear, clear text
if(data.clear){
textarea.value = '';
}
});
// Handle Input
textarea.addEventListener('keydown', function(event){
if(event.which === 13 && event.shiftKey == false){
// Emit to server input
socket.emit('input', {
name:username.value,
message:textarea.value
});
event.preventDefault();
}
})
// Handle Chat Clear
clearBtn.addEventListener('click', function(){
socket.emit('clear');
});
// Clear Message
socket.on('cleared', function(){
messages.textContent = '';
});
}
})();
</script>
</body>
</html>
mongodb driver "mongodb": "^3.1.0-beta4",
mongodb database version v3.2.20
"socket.io": "^2.1.1"`
This problem bugs me for hours and I have no clues. So apprecite your help.

Resources