Develop a JavaScript application with MongoDB on Azure
To create, move, or use a mongoDB database to Azure, you need a Cosmos DB resource. Learn how to create the resource and use your database.
Create and use database with VS Code extension
Create a Cosmos resource first because this will take several minutes.
In Visual Studio Code, select the Azure icon in the left-most menu, then select the Databases section.
If the Databases section isn't visible, make sure you have checked the section in the top Azure ... menu.
In the Databases section of the Azure explorer, select your subscription with a right-click, then select Create Server.
In the Create new Azure Database Server Command Palette, select Azure Cosmos DB for MongoDB API.
Follow the prompts using the following table to understand how your values are used. The database may take up to 15 minutes to create.
Property Value Enter a globally unique Account name name for the new resource. Enter a value such as cosmos-mongodb-YOUR-NAME, for your resource. ReplaceYOUR-NAMEwith your name or unique ID. This unique name is also used as part of the URL to access the resource in a browser.Select or create a resource group. Create a new resource group named js-demo-mongodb-web-app-resource-group-YOUR-NAME-HERE.Location The location of the resource. For this tutorial, select a regional location close to you. Creating the resource may take up to 15 minutes. You can skip to the next section if you are time-restricted but remember to come back to finish this section in a few minutes.
Add firewall rule for your client IP address
You need to use the Azure CLI or the Azure portal to configure a firewall rule.
Get the MongoDB connection string for your resource
- Select the Azure explorer from the Activity bar.
- Select the Cosmos DB from the Side bar.
- Right-click on the database and select Copy connection string.
Use the Azure Cosmos DB emulator for local development
Learn more about the Azure Cosmos DB emulator:
- Install and use the Azure Cosmos DB Emulator for local development and testing
- Start the emulator from command prompt as an administrator
Use native SDK packages to connect to MongoDB on Azure
The mongoDB database on Cosmos DB uses npm packages already available, such as:
Install mongodb SDK
To connect and use your mongoDB on Azure Cosmos DB with JavaScript and mongodb, use the following procedure.
Make sure Node.js and npm are installed.
Create a Node.js project in a new folder:
mkdir DataDemo && \ cd DataDemo && \ npm init -y && \ npm install mongodb && code .The command:
- Creates a project folder named
DataDemo - Changes the Bash terminal into that folder
- Initializes the project, which creates the
package.jsonfile - Installs the SDK
- Opens the project in Visual Studio Code
- Creates a project folder named
Create JavaScript file to bulk insert data into MongoDB database
In Visual Studio Code, create a
bulk_insert.jsfile.Download the MOCK_DATA.csv file and place it in the same directory as
bulk_insert.js.Copy the following JavaScript code into
bulk_insert.js:const { MongoClient } = require('mongodb'); const ObjectId = require('mongodb').ObjectID; require('dotenv').config(); const fs = require('fs'); const parse = require('csv-parser') const { finished } = require('stream/promises'); const DATABASE_URL = process.env.YOUR_RESOURCE_PRIMARY_CONNECTION_STRING ? process.env.YOUR_RESOURCE_PRIMARY_CONNECTION_STRING : 'mongodb://localhost:27017'; const DATABASE_NAME = process.env.DATABASE_NAME || 'my-tutorial-db'; const DATABASE_COLLECTION_NAME = process.env.DATABASE_COLLECTION_NAME || 'my-collection'; const csvFile = './books.csv' let mongoConnection = null; let db = null; let collection = null; // insert each row into MongoDB const insertData = async (readable) =>{ let i = 0; for await (const row of readable) { console.log(`${i++} = ${JSON.stringify(row.goodreads_book_id)}`); await collection.insertOne(row); } } const bulkInsert = async () => { mongoConnection = await MongoClient.connect(DATABASE_URL, { useUnifiedTopology: true }); db = mongoConnection.db(DATABASE_NAME); collection = await db.collection(DATABASE_COLLECTION_NAME); // read file, parse CSV, each row is a chunk const readable = fs .createReadStream(csvFile) .pipe(parse()); // Pipe rows to insert function await insertData(readable) await mongoConnection.close(); } bulkInsert().then(() => { console.log('done'); }).catch(err => { console.log(`done + failed ${err}`) })Replace the following in the script with your resource information:
- YOUR_RESOURCE_PRIMARY_CONNECTION_STRING
Run the script.
node bulk_insert.js
Create JavaScript code to use MongoDB
In Visual Studio Code, create a
index.jsfile.Copy the following JavaScript code into
index.js:const { MongoClient } = require('mongodb'); const ObjectId = require('mongodb').ObjectID; // read .env file require('dotenv').config(); /* eslint no-return-await: 0 */ const DATABASE_URL = process.env."YOUR_RESOURCE_PRIMARY_CONNECTION_STRING" ? process.env."YOUR_RESOURCE_PRIMARY_CONNECTION_STRING" : 'mongodb://localhost:27017'; const DATABASE_NAME = process.env.DATABASE_NAME || 'my-tutorial-db'; const DATABASE_COLLECTION_NAME = process.env.DATABASE_COLLECTION_NAME || 'my-collection'; let mongoConnection = null; let db = null; const insertDocuments = async ( documents = [{ a: 1 }, { a: 2 }, { a: 3 }] ) => { // check params if (!db || !documents) throw Error('insertDocuments::missing required params'); // Get the collection const collection = await db.collection(DATABASE_COLLECTION_NAME); // Insert some documents return await collection.insertMany(documents); }; const findDocuments = async ( query = { a: 3 } ) => { // check params if (!db) throw Error('findDocuments::missing required params'); // Get the collection const collection = await db.collection(DATABASE_COLLECTION_NAME ); // find documents return await collection.find(query).toArray(); }; const removeDocuments = async ( docFilter = {} ) => { // check params if (!db ) throw Error('removeDocuments::missing required params'); // Get the documents collection const collection = await db.collection(DATABASE_COLLECTION_NAME); // Delete document return await collection.deleteMany(docFilter); }; const connect = async (url) => { // check params if (!url) throw Error('connect::missing required params'); return MongoClient.connect(url, { useUnifiedTopology: true }); }; /* eslint consistent-return: [0, { "treatUndefinedAsUnspecified": false }] */ const connectToDatabase = async () => { try { if (!DATABASE_URL || !DATABASE_NAME) { console.log('DB required params are missing'); console.log(`DB required params DATABASE_URL = ${DATABASE_URL}`); console.log(`DB required params DATABASE_NAME = ${DATABASE_NAME}`); } mongoConnection = await connect(DATABASE_URL); db = mongoConnection.db(DATABASE_NAME); console.log(`DB connected = ${!!db}`); return !!db; } catch (err) { console.log('DB not connected - err'); console.log(err); } }; module.exports = { insertDocuments, findDocuments, removeDocuments, ObjectId, connectToDatabase };Replace the following in the script with your resource information:
- YOUR_RESOURCE_PRIMARY_CONNECTION_STRING
Run the script.
node index.js
Next steps
Povratne informacije
Pošalјite i prikažite povratne informacije za