Node & MongoDB - Embedded Document



To insert embedded document(s) in a collection of a database, you can use collection.insertOne() or collection.insertMany() methods to insert one or multiple documents.

database.collection("sampleCollection").insertOne(firstDocument, function(error, res) {
   if (error) throw error;
   console.log("1 document inserted");
});
database.collection("sampleCollection").insertMany(documents, function(error, res) {
   if (error) throw error;
   console.log("Documents inserted: " + res.insertedCount);
});

Example

Try the following example to insert documents in a mongodb collection −

Copy and paste the following example as mongodb_example.js −

const MongoClient = require('mongodb').MongoClient;

// Prepare URL
const url = "mongodb://localhost:27017/";

const firstPost = {
   title : 'MongoDB Overview',
   description : 'MongoDB is no SQL database',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   comments: [{
      user: 'user1',
      message: 'My First Comment',
      dateCreated: '20/2/2020',
      like: 0
   },
   {
      user: 'user2',
      message: 'My Second Comment',
      dateCreated: '20/2/2020',
      like: 0
   }]
};
// make a connection to the database
MongoClient.connect(url, function(error, client) {
   if (error) throw error;
   console.log("Connected!");
   // Connect to the database
   const database = client.db('posts');     
   database.collection("samplePost").insertOne(firstPost, function(error, res) {
   if (error) throw error;
      console.log("1 document inserted");
   });  
   // close the connection
   client.close();
});

Output

Execute the mysql_example.js script using node and verify the output.

node mongodb_example.js
Connected.
1 document inserted
Advertisements