わかりましたので、このSchemaOptions、Schema、Constructor、およびvirtualがあります。
var schemaOptions = {
toObject: { virtuals: true }, toJSON: { virtuals: true }
};
var clientSchema = mongoose.Schema ({
company: { type: String, trim: true, required: true, unique: true },
monthly_cost: { type: Number, trim: true, required: true },
sms_cost: { type: Number, trim: true, required: true },
...
}, schemaOptions);
var Client = mongoose.model('Client', clientSchema);
clientSchema.virtual('creationDate').get(function () {
return dateFormat(this._id.getTimestamp(), 'isoDate');
});
さらに下に、次のルートがあります: (for ループ内のコメント付きコードに注意してください。このコメントは後で削除します)
app.get('/superadmin', function(req, res) {
Client.find({}, 'company monthly_cost sms_cost', function (err, docs) {
if (err) return handleError(err);
for (var i = 0, tot=docs.length; i < tot; i++) {
// docs[i].creationDate = 'strange variable ' + i;
}
console.log(docs);
res.render('superadmin/index', {
title: 'Superadmin',
docs: docs,
path: req.route.path,
});
});
});
私のJadeビューには、次のコードがあります。
p #{docs};
each client in docs
tr
td #{client.company}
td #{client.creationDate}
...
しかし、ここで問題が発生します。
私のルートではconsole.log(docs);
、「YYYY-MM-DD」に似た文字列を出力しますが、これは予想どおりであり、適切です。
私の見解の早い段階で、console.log(docs);
これは正しい文字列 'YYYY-MM-DD' も出力します。
しかし、私のビューでは #{client.creationDate} は何も出力しません!! 理由がわかりません。
次のように、for ループでコメント行をアクティブにすると、次のようになります。
for (var i = 0, tot=docs.length; i < tot; i++) {
docs[i].creationDate = 'strange variable ' + i;
}
...#{client.creationDate}
出力します'strange variable [0-2]'
。しかし、私の前の 2 つconsole.log(docs)
は、予想される creationDate 文字列を出力します。
私はこれを理解していません.. creationDate は同時に2つの変数のようです。
Mongoose Virtuals は私を夢中にさせています。フェッチされた mongoose オブジェクトにその場でキー値を追加できるように見えるのに、なぜ私が彼らに文句を言っているのか本当に理解できません。わかりました、それらはconsole.logに表示されません...しかし、それらは何とかそこにあり、次のように使用できます:#{client.creationDate}
私の見解では。