I want to use data from my MongoDB for displaying on HTML code via Node.js. So far, I know how to insert information from a HTML5 formular into my MongoDB and how I read out this information - but the result of my find()
is like:
[ { name: 'Mr. Banana', _id: 123aclongvalueinHEX001c000001 } ]
This is the simple result example display on my node.exe
cmdshell of the function:
People.find(
{},
['name'],
function(err, docs) {
if (!err){
console.log(docs);
}
else { throw err;}
}
);
People
is the Mongoose schema and has some attributes, in this example I am only searching for all names with only one entity saved in People
.
So the question is, and I feel like searching for it forever, how do I only extract Mr. Banana
without the whole [{ name: and id}]
- thing? I suppose there is some function or option for it, but I just can't find it! I could invent a function to trim it by leftstr etc. this would be my emergency solution.
If you only want to output the name
property of the first document in your results:
console.log(docs[0].name);
If you want to prevent the _id
from even being included in the returned docs, see this post.
I've got the hint that mongoose has functions called querystreams. That leads to my solution.
var Bericht = new Schema({
name : String
, mail : String
, standort : String
, betreff : String
, inhalt : String
, datum : Date
});
var Bericht = mongoose.model('Bericht', Bericht);
var stream = Bericht.find().stream()
, names = []
, mails = []
, standorts = []
, betreffs = []
, inhalts = []
, datums = []
, i=0;
function closeHandler() {
function closeHandler() {
console.log(JSON.stringify(names));
};
stream.on('data', function (doc) {
if (doc.name) {
names.push(doc.name);
mails.push(doc.mail);
standorts.push(doc.standort);
betreffs.push(doc.betreff);
inhalts.push(doc.inhalt);
datums.push(doc.datum);
}
})
stream.on('close', closeHandler)
My schema has more than names, in this case 6 attributes. After using the stream.on function, I got everything out of my database into an array like mails[1] is the mail of the second entry in my mongodb. With that, I can easily display the whole content of my database in a html by using functions. Maybe this is too much, but due of liking this board, I'll complete this thread.
With this function, you are building a simple table of all names as return value:
function namestable(){
value = "<table border='1'><tr><th>Namen</th></tr>"
for(var i=0;i<names.length;i++){
value+="<tr><td>"+names[i]+"</td>";
;}
value+="</table>";
return value;
}
So you just have to add this function into your nodejs, when you are building the html code:
var body = '<html>'+
'<head>'+
'<meta http-equiv="Content-Type" content="text/html; '+
'charset=UTF-8" />'+
'</head>'+
'<body>'+
'<form action="/upload" method="post">'+
namestable()+
'<input type="submit" value="Hario" />'+
'</form>'+
'</body>'+
'</html>';
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(body);
response.end();
I like :)