Insert a document
suggest changeInsert one document into myCollection with the properties greetings and farewell. Since driver 3.x, MongoClient.connect passes a client, and the database name is selected with client.db(). Driver 4 and later drop the callback and return a promise.
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
MongoClient.connect(url, function (err, client) {
if (err) throw err;
var db = client.db('test');
db.collection('myCollection').insertOne({
greetings: 'Hellu',
farewell: 'Bye'
}, function (err, result) {
if (err) throw err;
console.log('Inserted a document into the myCollection collection!');
client.close();
});
});
Collection method insertOne()
db.collection(collection).insertOne(document, options, callback)
| Argument | Type | Description |
|---|---|---|
collection |
string | Name of the collection |
document |
object | The document to insert |
options |
object | Optional settings. The default is null. |
callback |
function | Called when the insert finishes. Removed in driver 4. |
The callback function takes two arguments
err: Error - If an error occurs theerrargument will be definedresult: object - An object containing details about the insert operation
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents