0
私はちょうどMEANを学習し始めました。ノードサーバに作ったデータベースの特定のフィールドだけを表示したいと思います。私はExpressを使っています。ここまでは私のコードです。MongoDB&NodeJS:サーバ上のJadeファイルに特定のフィールドを表示する方法
index.js
router.get('/generate', function(req, res) {
// get out mongoclient to work with our mongo server
var MongoClient = mongodb.MongoClient;
// where the mongodb server is
var url = 'mongodb://localhost:27017/data';
MongoClient.connect(url, function(err, db) {
if(err) {
console.log('Unable to connect to server', err);
} else {
console.log('Connection established');
var collection = db.collection('compliments');
collection.find({}).toArray(function(err, result) {
if (err) {
res.send(err);
} else if (result.length) {
res.json(result); // problem here
} else {
res.send('No documents found');
}
db.close();
});
}
});
})。
generate.jade
doctype html
html
head
title("Compliment Generator")
body
h1 !{title}
block content
h3.
!{compliment}
これは、ローカルホスト上で次のようになります。それが唯一の「コンテンツ」を表示するように、3000 /生成
[{"_id":"570b50f8265f2536d2fd6ed6","type":"compliment","content":"You are absolutely gorgeous."},{"_id":"570b50f8265f2536d2fd6ed7","type":"compliment","content":"You are wonderful."},{"_id":"570b50f8265f2536d2fd6ed8","type":"compliment","content":"I could look at you all day."}]
は、どのように私はそれを作るのですか?ありがとう!
ありがとうございます! [:今ではこのように表示されています{「内容」:「あなたは絶対に豪華です。」}、{「内容」:「あなたは素晴らしいです。」}、{「内容」:「私は一日中、あなたに見ることができます。」} ]、私はどのようにして "コンテンツ"の部分を取り除き、実際の褒め言葉を見せますか? – user298519
キー値のペアのような要素にアクセスすると、 'result [0] .content'は最初の要素の' content'フィールドの値を返します。あなたは、forループまたは必要な他の必要な繰り返しパターンを持つものを反復することができます。 – Vistari
私の前のコメントは何らかの理由でそれを編集することはできません。 JSON文字列の場合は、JSON.parse(result);という構文でjavascriptオブジェクトに解析する必要があります。 – Vistari