npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongoose-i18n-extra

v0.1.5

Published

mongoose plugin to manage i18n fields

Downloads

351

Readme

mongoose-i18n-extra

Build Status Code Climate

Mongoose schema plugin for multilingual fields, largely inspired by mongoose-intl plugin.

There are several mongoose plugins dealing already with i18n, the most popular being mongoose-intl, but they all changing the translated field into a subdocument containning all translated value.

This plugin only add a new virtual field _i18n with all translations inside, except the default language, which is stored in the main translated field. It's easier to use on an existing database. No need to migrate all documents, you can use this plugin straighforward.

Installation

$ npm install mongoose-i18n-extra --save

Overview

Adding plugin to the schema

Schema definition with i18n option enabled for some fields:

const mongoose          = require('mongoose');
const mongooseI18nExtra = require('mongoose-i18n-extra');
const { Schema }        = mongoose;

var BlogPost = new Schema({
    title  : { type: String, i18n: true },
    body   : { type: String, i18n: true }
});

Note: i18n option can be enabled for String type only.

Adding plugin to the schema:

BlogPost.plugin(mongooseI18nExtra, { languages: ['en', 'de', 'fr'], defaultLanguage: 'en' });

Plugin options

  • languages - required, array with languages, suggested to use 2- or 3-letters language codes using ISO 639 standard
  • defaultLanguage - optional, if omitted the first value from languages array will be used as a default language

Database representation

BlogPost schema described above will be translated to the following document in the Mongo collection:

{
    "_id": ObjectId(...),
    "title": "...",
    "body": "...",
    "_i18n": {
        "en": {"title": "...", "body": "..."},
        "de": {"title": "...", "body": "..."},
        "fr": {"title": "..., "body": "..."}"
    }
}

Usage

i18n-enabled field is converted to a virtual path and continue interacting as a string, not an object. It means that you can read it and write to it any string, and it will be stored under default language setting.

Other languages values can be set by using model.set() method. Pass an object with multiple languages instead of the string to set all values together. See examples below.

Multilingual fields can be set with 2 ways:

var BlogPostModel = mongoose.model('Post', BlogPost);

var post = new BlogPostModel();

post.title = 'Title on default language'; // default language definition, will be stored to title

post.set('title_de', 'German title'); // any other language value definition will be stored to _i18n.de.title

// you can also set multiple value at once
post.set(
"_i18n": {
    "en": {"title": "...", "body": "..."},
    "de": {"title": "...", "body": "..."},
    "fr": {"title": "..., "body": "..."}"
});

await post.save();

Values can be read using the same options:

var BlogPostModel = mongoose.model('Post', BlogPost);

const post = await BlogPostModel.findOne({...});

console.log(post.title); // 'Title on default language'
console.log(post.get('title_de')); // 'Another German title'

This plugin is also compliant with the plugin mongoose-lean-virtuals which exposes the virtual fields:

const post = await BlogPostModel.findOne({...}).lean({virtuals: ['_i18n']});

console.log(post.title); // 'Title on default language'
console.log(post._i18n); // { "de": {description: "..."}, "en": {"description": "..."}, "fr": {description: "..."} }

Language methods

The current language can be set/changed on 1 level for the moment:

  • Document level: affects only some document (each particular model instance)

Document level

Each document will receive the following language methods:

  • getLanguages() - returns an array of available languages
  • getLanguage() - returns current document's language
  • setLanguage(lang) - changes document's language to a new one, the value should be equal to the one of available languages
  • unsetLanguage() - removes previously set document-specific language, schema's default language will be used for the translation

Usage examples:

const posts = await BlogPostModel.find({});

  console.log(JSON.stringify(posts)); // [{ _id: '...', title: 'Title 1 on default language' },
                                      //  { _id: '...', title: 'Title 2 on default language' }, ...]

  posts[0].getLanguages(); // [ 'en', 'de', 'fr' ]
  posts[0].getLanguage(); // 'en'

  posts[0].setLanguage('de');
  console.log(JSON.stringify(posts)); // [{ _id: '...', title: 'Another German title' },
                                      //  { _id: '...', title: 'Title 2 on default language' }, ...]

  BlogPostModel.setDefaultLanguage('fr'); // schema-level language change (see documentation below)
  console.log(JSON.stringify(posts)); // [{ _id: '...', title: 'Another German title' }, // still 'de'
                                      //  { _id: '...', title: 'French title 2' }, ...]

  posts[0].unsetLanguage();
  console.log(JSON.stringify(posts)); // [{ _id: '...', title: 'French title 1' },
                                      //  { _id: '...', title: 'French title 2' }, ...]
});

Intl-based String type options

default and required options are applied to the default language field only.

2 new options were added for all lang-fields: defaultAll and requiredAll.

Example:

var BlogPost = new Schema({
    title  : { type: String, i18n: true, default: 'Some default title', requiredAll: true },
    body   : { type: String, i18n: true }
});

All others options and validators (e.g. lowercase, uppercase, trim, minlength, maxlength, match, etc.) will be used for all languages. But please be careful with some of them like enum which may not be relevant for multilingual text fields, and indexes which will be added for all fields as well.

TODO

  • define as a global plugin which will be applied to all schemas.
  • set language at schema level
  • set language at connection level

Alternative plugins