0

我是 node.js 和sails 的新手,但它很简单,所以我喜欢它:) 我实际上正在使用带有MongoDB anssails-mongo 的sails Framework 0.10rc3。

我知道水线的贡献者并不喜欢模型中的嵌入式文档,如 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' 是一个跨度(所以 this.end 可以工作,而不是 this.proj.end)还是 'this' 是一个 ProjetSpan(所以 this.proj.end 可以工作,但不是 this.end)?

最后,如何使 this.end(当前 span 中的变量)和 this.proj.end(当前文档关联中的变量)在这个嵌入式上下文中工作?

4

1 回答 1

1

Waterline 根本不支持嵌入文档,除了提供json数据类型。因此,您的模型示例在 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;
       }

    }



}

在实例方法(like beforeand afterhere)中,this指的是整个实例对象。您将希望通过检查来增强该代码,以确保它this.proj是一个对象(即,它是用 填充的ProjetSpan.find({}).populate('project')),并且它this.spans.end确实this.spans.start存在(因为 Waterline 不验证嵌入的 JSON)。

于 2014-03-05T17:06:54.697 回答