我在node.js和sails方面都是新手,但很简单,所以我很喜欢它:)我实际上是在使用SailsFramework0.10rc3和MongoDB。
我知道在mongodb (https://github.com/balderdashy/sails-mongo/issues/44#issuecomment-35561040)模型中,水线的贡献者并不是嵌入式文档的忠实拥趸,但无论如何,我想知道'this‘变量在它们中是如何工作的,以及如何检索内部数组中的当前元素。
下面是模型的一个例子(我们可以称之为ProjetSpan):
module.exports = {
attributes: {
proj:
{
model:'Projet'
},
spans:
{
start:
{
type: 'DATETIME',
required: true,
datetime: true,
before: function() {
if (this.end < this.proj.end)
return this.end;
else
return this.proj.end;
}
},
end:
{
type: 'DATETIME',
required: true,
datetime: true,
after: function() {
if (this.start > this.proj.start)
return this.start;
else
return this.proj.start;
}
}
}
}
};在这种情况下,“这”将如何运作?“这”是一个跨度(因此this.end会工作,而不是this.proj.end)还是“ProjetSpan”(ans这样this.proj.end工作,而不是this.end)?
最后,如何使this.end (当前span中的变量)和this.proj.end (当前文档关联中的变量)在此嵌入式上下文中工作?
发布于 2014-03-05 17:06:54
除了提供json数据类型之外,Waterline根本不支持嵌入式文档。因此,您的模型示例在Sails中不起作用,需要将其重写为如下所示:
module.exports = {
attributes: {
proj: {
model:'projet'
},
spans: {
type: 'json'
},
before: function() {
if (this.spans.end < this.proj.end) {
return this.spans.end;
} else {
return this.proj.end;
}
},
after: function() {
if (this.spans.start > this.proj.start) {
return this.spans.start;
} else {
return this.proj.start;
}
}
}在实例方法(如before和after )中,this引用整个实例对象。您需要使用检查来增强该代码,以确保this.proj是一个对象(即,它是用ProjetSpan.find({}).populate('project')填充的),并且this.spans.end和this.spans.start确实存在(因为Waterline不验证嵌入式JSON)。
https://stackoverflow.com/questions/22196666
复制相似问题