在 Sails 中使用数组属性类型

Using Array Attribute Type in Sails

我想在我的应用程序中使用 sails 属性类型 'array',但我在任何地方都找不到这方面的文档。

我想做以下事情:

module.exports = {
 attributes : {
  images: {
   type: ['string']
  },
  location: {
   type: ['float','float']
  }
 }
}

image 是一个数组,它将包含一个图像 url 列表,location 将包含 2 个浮点数。这会在 sail 中起作用吗?否则我怎么能让它工作。 谢谢

PS:我只和 MongoDB

一起工作

据我所知,只能这样指定:

module.exports = {
    attributes : {
        images: {
            type: 'array'
        },
        location: {
            type: 'array'
        }
    }
}

Sails ORM Attributes

sailsjs提供了一个功能来解决你的问题,你可以试试这个

module.exports = {
 attributes : {
  images: {
   type: 'string'
  },
  location: {
   type: 'json'
  }
 }
}

从 Sails 1.0 开始,类型 array 不再受支持。

The type "array" is no longer supported. To use this type in your model, change type to one of the supported types and set the columnType property to a column type supported by the model's adapter, e.g. { type: 'json', columnType: 'array' }

解决方案一

设置属性以存储图像数组和位置数组...

module.exports = {
  attributes : {
    images: {
      type: 'json',                           
      columnType: 'array'
    }
    location: {
      type: 'json',
      columnType: 'array'
    }
  }
}

解决方案二

一个更优雅的解决方案是设置一个对象来存储文件名和位置数据

module.exports = {
  attributes : {
    images: {
      type: 'json'
    }
  }
}

然后在您的控制器中将对象属性存储为数组...

let imageData = {
  filename: ["image1.jpg", "image2.jpg", "image3.jpg"],
  location: [154.123123, 155.3434234, 35.12312312]
};

Images.create({images:imageData});

将数据存储到 json 对象时的一些问题是像“image1.jpg、image2.jpg、image3.jpg”这样的字符串将存储在 MongoDb 中不用担心……呵呵。确保在发布时您可能需要拆分数据 .split(',').

对于sails 1.0,对于array,也许你可以尝试这种方式,我只是为了分享。 您也可以在更新和处理本机 query() 之前替换并删除水线更新的属性。希望对你有帮助。

        variants:
        {
            type: 'json',
            columnType: 'array',
            custom: (value) =>
            {
                /*
                  [
                        code    : unique, string
                        name    : string, maxLength[30]
                        cost    : number, isFinite
                        price   : number, isFinite
                        default : boolean
                  ]
                */
                return _.isArray(value)
                &&     _.every(value, (variant1) =>
                {
                    return _.countBy(value, (variant2) =>
                    {
                        return variant2.code == variant1.code ? 'eq' : 'uneq';
                    }).eq <= 1
                    && _.isString(variant1.name) && variant1.name.length < 30
                    && _.isNumber(variant1.cost) && _.isFinite(variant1.cost)
                    && _.isNumber(variant1.price) && _.isFinite(variant1.price)
                    && _.isBoolean(variant1.default);
                });
            },
        },