【问题标题】:Are Mongoose virtuals messed up?Mongoose virtuals 是不是搞砸了?
【发布时间】:2013-09-21 22:40:28
【问题描述】:

好的,所以我有这个 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]'。但是我之前的两个console.log(docs) 仍然会输出预期的creationDate 字符串。

这个我没看懂。。好像creationDate同时是两个变量。

Mongoose Virtuals 快把我逼疯了,我真的不明白为什么我要向他们抱怨,因为它似乎可以动态地将键值添加到获取的 mongoose 对象。好的,它们不会出现在 console.log 中......但它们以某种方式存在,我可以像这样使用它们:#{client.creationDate} 在我看来。

【问题讨论】:

  • creationDate 符合预期时,console.log(docs) 的输出是什么?
  • 当我通过 console.log 输出整个文档时,.creationDate 的输出是正确的。也就是虚函数生成的“YYYY-MM-DD”。但是当我尝试在路由中只输出一个这样的 .creationDate 时:console.log(doc[0].creationDate) 就像值不再存在一样......

标签: node.js mongodb express mongoose pug


【解决方案1】:

这段代码有问题:

var Client = mongoose.model('Client', clientSchema);

clientSchema.virtual('creationDate').get(function () {
  return dateFormat(this._id.getTimestamp(), 'isoDate');
});

在将架构“编译”为模型之前,您必须完全配置它。它不是动态的。编译模型后,对架构的进一步更改不会生效。

【讨论】:

  • 你是我的上帝。在我自己解决这个问题之前,我可能不会花很长时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-15
  • 2012-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多