Categories
MongoDB

Using MongoDB with Mongoose

To make MongoDB database manipulation easy, we can use the Mongoose NPM package to make working with MongoDB databases easier.

In this article, we’ll look at how to use Mongoose to manipulate our MongoDB database.

Getting Started with Mongoose

We can install the package by running:

npm install mongoose --save

Then we can use it by writing:

const mongoose = require('mongoose');
const connection = "mongodb://localhost:27017";
mongoose.connect(connection, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', () => console.error('connection error:'));
db.once('open', () => {
  console.log('connected')
});

We connect th our MongoDB database with Mongoose by using the mongoose.connect method.

Then to see if we connected successfully, we can listen to the open event.

Defining Schemas

Now we can define a schema to restrict what we can put on our documents.

This is something that’s not available with the native MongoDB client.

For example, we can write:

const mongoose = require('mongoose');
const connection = "mongodb://localhost:27017";
mongoose.connect(connection, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', () => console.error('connection error:'));
db.once('open', () => {
  console.log('connected')
});

const kittySchema = new mongoose.Schema({
  name: String
});

const Kitten = mongoose.model('Kitten', kittySchema);
const baby = new Kitten({ name: 'james' });
baby.save((err, baby) => {
  if (err) {
    return console.error(err);
  }
  console.log(baby.name);
});

We create the schema with the mongoose.Schema constructor.

The object has the fields as the keys and the data type as the values.

Then we define the model with the mongoose.model method.

Then we use the Kitten constructor, and then we call save to save the Kitten object to the database.

The _id will automatically be generated for each inserted entry.

If we want to get the entries, then we can call the find method:

const mongoose = require('mongoose');
const connection = "mongodb://localhost:27017/test";
mongoose.connect(connection, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', () => console.error('connection error:'));
db.once('open', () => {
  console.log('connected')
});

const kittySchema = new mongoose.Schema({
  name: String
});

const Kitten = mongoose.model('Kitten', kittySchema);
const baby = new Kitten({ name: 'james' });
baby.save((err, baby) => {
  if (err) {
    return console.error(err);
  }
  console.log(baby.name);
});

Kitten.find((err, kittens) => {
  if (err) return console.error(err);
  console.log(kittens);
})

If we want to find a specific entry we can pass in an object to the first argument of find :

const mongoose = require('mongoose');
const connection = "mongodb://localhost:27017/test";
mongoose.connect(connection, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', () => console.error('connection error:'));
db.once('open', () => {
  console.log('connected')
});

const kittySchema = new mongoose.Schema({
  name: String
});

kittySchema.methods.speak = function () {
  console.log(`hello ${this.name}`);
}

const Kitten = mongoose.model('Kitten', kittySchema);
const baby = new Kitten({ name: 'james' });
baby.speak();
baby.save((err, baby) => {
  if (err) {
    return console.error(err);
  }
  console.log(baby.name);
});

Kitten.find({ name: /^james/ },(err, kittens) => {
  if (err) return console.error(err);
  console.log(kittens);
})

If we want to add methods, we can write:

const mongoose = require('mongoose');
const connection = "mongodb://localhost:27017/test";
mongoose.connect(connection, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', () => console.error('connection error:'));
db.once('open', () => {
  console.log('connected')
});

const kittySchema = new mongoose.Schema({
  name: String
});

kittySchema.methods.speak = function () {
  console.log(`hello ${this.name}`);
}

const Kitten = mongoose.model('Kitten', kittySchema);
const baby = new Kitten({ name: 'baby' });
baby.speak();
baby.save((err, baby) => {
  if (err) {
    return console.error(err);
  }
  console.log(baby.name);
});

Kitten.find((err, kittens) => {
  if (err) return console.error(err);
  console.log(kittens);
})

We added a method to the Kitten model by adding a method to the methods object property.

Conclusion

We can create schemas, add items, and find items with Mongoose.

Categories
MongoDB

Node.js Basics — Creating and Deploying Packages

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Creating NPM Packages

We can create our own NPM packages to do that, we run npm add user so we can log into NPM to create our package.

Once we typed in the command, we’ll have to enter a username, password, and email address for our account to create an account on NPM.

The email wil be public.

Then we run npm init to create our package’s package.json file.

Once we answered all the questions, we should get something like:

{
  "name": "npm-example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Once we’re done, we can run npm publish to publish our package.

Then once we published our package, we can run:

npm install npm-example

to install our package.

To update the version of our package, we run npm version patch .

Then we can run npm publish to publish the package with the later version.

To keep some files from being published in a package, we can create a .npmignore file which follows the same rules as the .gitignore file.

Conclusion

We can create NPM packages easily with npm .

All we have to do is enter some package data and publish the package.

Categories
MongoDB Node.js Basics

Node.js Basics — MongoDB Collations

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Collations

Collations are sets of sorting rules that are used when we do string order for specific languages and locales.

We can specify the collation property when we create the collection.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const db = client.db("test");
    await db.dropCollection('test');
    await db.createCollection("test", {
      collation: { locale: "en" },
    });
    const testCollection = await db.collection('test');
    await testCollection.dropIndexes();
    await testCollection.deleteMany({})
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    const query = {};
    const projection = { name: 1 };
    const cursor = testCollection
      .find(query)
      .project(projection);
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We call createCollection with the collection name as the first argument.

The 2nd argument is an object where we have the collation property to set the collation rule.

Then we call find to query the collection.

Assign a Collation to an Index

We can also assign a collection to an index.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const db = client.db("test");
    await db.dropCollection('test');
    await db.createCollection("test");
    const testCollection = await db.collection('test');
    await testCollection.createIndex(
      { 'name': 1 },
      { 'collation': { 'locale': 'en' } });
    await testCollection.dropIndexes();
    await testCollection.deleteMany({})
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    const query = { name: 'apple' };
    const options = { "collation": { "locale": "en_US" } };
    const cursor = testCollection
      .find(query, options)
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We have:

await testCollection.createIndex(
      { 'name': 1 },
      { 'collation': { 'locale': 'en' } });

We called createIndex with the fields to index in the first argument.

The 2nd argument has the collation options.

Then we can use it by writing:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const db = client.db("test");
    await db.dropCollection('test');
    await db.createCollection("test");
    const testCollection = await db.collection('test');
    await testCollection.createIndex(
      { 'name': 1 },
      { 'collation': { 'locale': 'en' } });
    await testCollection.dropIndexes();
    await testCollection.deleteMany({})
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    const cursor = testCollection
      .find()
      .sort({ "name": -1 });
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We sort the name field with the sort method in descending order.

Conclusion

We can add collations applying sorting rules for a specific language with MongoDB.

Categories
MongoDB Node.js Basics

Node.js Basics — MongoDB Collation Rules for Deletion and Aggregation

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Collation and findOneAndDelete

We can set collation rules with the findOneAndDelete method.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const db = client.db("test");
    await db.dropCollection('test');
    await db.createCollection("test");
    const testCollection = await db.collection('test');
    await testCollection.createIndex(
      { 'name': 1 },
      { 'collation': { 'locale': 'en' } });
    await testCollection.dropIndexes();
    await testCollection.deleteMany({})
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    testCollection
      .findOneAndDelete(
        { qty: { $gt: "5" } },
        { collation: { locale: "en", numericOrdering: true } },
      );
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We call findOneAndDelete with an object with the collation property to set the locale for the collation rule.

Collation and Aggregation

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const db = client.db("test");
    await db.dropCollection('test');
    await db.createCollection("test");
    const testCollection = await db.collection('test');
    await testCollection.createIndex(
      { 'name': 1 },
      { 'collation': { 'locale': 'en' } });
    await testCollection.dropIndexes();
    await testCollection.deleteMany({})
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "apples", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    const cursor = await testCollection
      .aggregate(
        [
          { $group: { "_id": "$name", "nameCount": { "$sum": 1 } } },
          { $sort: { "_id": 1 } },
        ],
        { collation: { locale: "en", numericOrdering: true } },
      );
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We call aggregate on testCollection with an array of aggregation rules that we want to apply.

We aggregate the names together and get the count of each name.

Then we sort by the _id value which is the value of the name field.

We then sort by the _id in ascending order.

In the 2nd argument, we set the collation rule.

Then the result we get from the cursor is:

{ _id: 'apples', nameCount: 2 }
{ _id: 'avocados', nameCount: 1 }
{ _id: 'oranges', nameCount: 1 }

Conclusion

We can use collation rules with the findOneAndDelete and aggregate methods of a MongoDB collection object.

Categories
MongoDB Node.js Basics

Node.js Basics — MongoDB Collation and Queries

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Collation Priority

If there are collation rules applied on the index and the query, then we can set the priority of the collation rule.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const db = client.db("test");
    await db.dropCollection('test');
    await db.createCollection("test");
    const testCollection = await db.collection('test');
    await testCollection.createIndex(
      { 'name': 1 },
      { 'collation': { 'locale': 'en' } });
    await testCollection.dropIndexes();
    await testCollection.deleteMany({})
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    const options = { "collation": { "locale": "en_US", "strength": 2 } };
    const cursor = testCollection
      .find({}, options)
      .sort({ "name": -1 });
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We have an options object to set the collation rule with the strength property.

The strength property determines the order of the collation rules we apply.

Collation Query

Collation is supported by find and sort queries.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const db = client.db("test");
    await db.dropCollection('test');
    await db.createCollection("test");
    const testCollection = await db.collection('test');
    await testCollection.createIndex(
      { 'name': 1 },
      { 'collation': { 'locale': 'en' } });
    await testCollection.dropIndexes();
    await testCollection.deleteMany({})
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    const cursor = testCollection
      .find({ name: "name" }, { collation: { locale: "en" } })
      .sort({ name: 1 });
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

The 2nd argument of find has an object with the collation property to set the collation rules.

We can also set the collation rule with the findOneAndUpdate method:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const db = client.db("test");
    await db.dropCollection('test');
    await db.createCollection("test");
    const testCollection = await db.collection('test');
    await testCollection.createIndex(
      { 'name': 1 },
      { 'collation': { 'locale': 'en' } });
    await testCollection.dropIndexes();
    await testCollection.deleteMany({})
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    testCollection
      .findOneAndUpdate(
        { qty: { $lt: 5 } },
        { $set: { rating: 5 } },
        { collation: { locale: "en" } },
      )
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

The 3rd argument has the collation property set to set the collation rule.

Conclusion

The collation rule priority can be set when we make queries. Also, we can set collation rules when we find, sort or update items.