首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >嵌入式文档中模型的“this”变量如何?

嵌入式文档中模型的“this”变量如何?
EN

Stack Overflow用户
提问于 2014-03-05 11:39:17
回答 1查看 135关注 0票数 0

我在node.js和sails方面都是新手,但很简单,所以我很喜欢它:)我实际上是在使用SailsFramework0.10rc3和MongoDB。

我知道在mongodb (https://github.com/balderdashy/sails-mongo/issues/44#issuecomment-35561040)模型中,水线的贡献者并不是嵌入式文档的忠实拥趸,但无论如何,我想知道'this‘变量在它们中是如何工作的,以及如何检索内部数组中的当前元素。

下面是模型的一个例子(我们可以称之为ProjetSpan):

代码语言:javascript
运行
复制
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 (当前文档关联中的变量)在此嵌入式上下文中工作?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-05 17:06:54

除了提供json数据类型之外,Waterline根本不支持嵌入式文档。因此,您的模型示例在Sails中不起作用,需要将其重写为如下所示:

代码语言:javascript
运行
复制
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;
       }

    }



}

在实例方法(如beforeafter )中,this引用整个实例对象。您需要使用检查来增强该代码,以确保this.proj是一个对象(即,它是用ProjetSpan.find({}).populate('project')填充的),并且this.spans.endthis.spans.start确实存在(因为Waterline不验证嵌入式JSON)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22196666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档