Currently everything I see are displaying an entire document, not just one field. How would I display just one field?
I have tried the following but I'm getting "undefined"s where I don't see anything displayed.
Way 1 main js:
// app.js
var schema = new mongoose.Schema({ a_field : String },
{ collection : 'the_col_with_data' });
var DocumentModel = mongoose.model('Doc', schema);
var a_document = DocumentModel.findOne({}, callback);
app.get('/', function(req, res) {
res.render('index', {
pass_var: a_document.a_field
});
});
Way 1 view:
// index.jade
#{ pass_var }
Way 2 main js:
// app.js
var schema = new mongoose.Schema({ a_field : String },
{ collection : 'the_col_with_data' });
var DocumentModel = mongoose.model('Doc', schema);
var a_document = DocumentModel.findOne({}, callback);
app.get('/', function(req, res) {
res.render('index', {
pass_var: a_document
});
});
Way 2 view:
// index.jade
#{ pass_var.a_field }
Interaction with mongoose is asynchronous. That means, you can't rely on the return value of a mongoose operation. You have to perform the logic that operates on your document within the callbacks. So in your case, a_document doesn't point to the document you're trying to find. Instead, you have to use the document within your callback:
app.get('/', function(req, res) {
DocumentModel.findOne({}, function(err, doc) {
if(err) {
res.send(500);
return;
}
res.render('index', {pass_var: doc});
});
});