Node.js Mongodb integration Insert a document

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Insert a document called 'myFirstDocument' and set 2 properties, greetings and farewell

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

const url = 'mongodb://localhost:27017/test';

MongoClient.connect(url, function (err, db) {
  if (err) throw new Error(err);
  db.collection('myCollection').insertOne({ // Insert method 'insertOne'
    "myFirstDocument": {
      "greetings": "Hellu",
      "farewell": "Bye"
    }
  }, function (err, result) {
    if (err) throw new Error(err);
    console.log("Inserted a document into the myCollection collection!");
    db.close(); // Don't forget to close the connection when you are done
  });
});

Collection method insertOne()

db.collection(collection).insertOne(document, options, callback)

ArgumentTypeDescription
collectionstringA string specifying the collection
documentobjectThe document to be inserted into the collection
optionsobject(optional) Optional settings (default: null)
callbackFunctionFunction to be called when the insert operation is done

The callback function takes two arguments

  • err : Error - If an error occurs the err argument will be defined
  • result : object - An object containing details about the insert operation


Got any Node.js Question?