02 / 19

How to create/ insert a record in MongoDB via Node.js?

Difficulty: 4/10
InsertOne/InsertMany, Error handling, Write concerns
MongoDB provides the following methods to insert documents into a collection:
  1. 1

    db.collection.insertOne()

  2. 2

    db.collection.insertMany()

db.collection.insertOne()
db.collection.insertMany()

Scenario Questions

0-2 years experience

  1. 1We have a simple Express endpoint that receives a JSON payload and needs to store it in a MongoDB collection. Walk me through the code you'd write to insert the document using the Node.js driver.
  2. 2If the insert fails because the database is down, how would you handle the error in your route handler?

2-5 years experience

  1. 1Our service now needs to insert multiple user activity logs at once. Which MongoDB driver method would you choose, and what considerations affect your choice?
  2. 2During a recent deployment, inserts started timing out. What steps would you take to debug the issue in a Node.js application?

5-8 years experience

  1. 1We are sharding a collection and need to ensure inserts are correctly routed and maintain write concern. How would you configure the Node.js driver and what trade‑offs do you consider?
  2. 2Explain how you would implement an idempotent insert operation to avoid duplicate records when the client retries after a network glitch.

8+ years experience

  1. 1Our platform is moving from a monolithic Node.js service to a microservices architecture, each service writing to its own MongoDB collection. How would you design a shared library for inserts that handles schema evolution, write concerns, and observability across teams?
  2. 2We need to migrate billions of existing records to a new schema while keeping the service online. Describe the strategy you’d use for inserting transformed documents with minimal downtime.

Follow-up Questions

  • What default write concern does the driver use, and when would you change it?
  • How does using insertMany affect atomicity compared to multiple insertOne calls?
  • Can you show how you'd log insert latency for monitoring purposes?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.