mongoose是虚拟的吗?

好吧,所以我有这个SchemaOptions,架构,构造和虚拟。

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'的string,这是预期的好。

早在我看来,我有: console.log(docs); 也输出正确的string:“YYYY-MM-DD”,这是预期的和好的。

但是:#{client.creationDate}在我看来doenst输出任何东西! 我不明白为什么。

如果我们现在激活我的for循环中的注释行,如下所示:

 for (var i = 0, tot=docs.length; i < tot; i++) { docs[i].creationDate = 'strange variable ' + i; } 

#{client.creationDate}将输出'strange variable [0-2]' 。 但是我的两个console.log(docs)仍然会输出期望的creationDatestring。

我不明白这个..似乎creationDate是两个variables在同一时间。

mongoose虚拟让我疯狂,我真的不明白为什么我会抱怨他们反正似乎可以添加键值飞到一个提取的mongoose对象。 好吧,他们不显示在console.log中,但他们在那里,我可以像这样使用它们: #{client.creationDate}在我的看法。

此代码不合格:

 var Client = mongoose.model('Client', clientSchema); clientSchema.virtual('creationDate').get(function () { return dateFormat(this._id.getTimestamp(), 'isoDate'); }); 

在将其“编译”为模型之前,您必须完全configuration您的模式。 这不是dynamic的。 一旦模型被编译,模式的进一步改变就不会产生影响。