Inserting a document

Let's test out our new db object by inserting a record into a collection:

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

MongoClient.connect('mongodb://localhost:27017/mongotest', (err, db)=>{
console.log('Connected to MongoDB!');

var collection = db.collection('testing');
collection.insert({'title': 'Snowcrash'}, (err, docs)=>{
/**
* on successful insertion, log to the screen
* the new collection's details:
**/
console.log(`${docs.ops.length} records inserted.`);
console.log(`${docs.ops[0]._id} - ${docs.ops[0].title}`);

db.close();

});
});

In the preceding code, we establish a connection to the database and execute a callback once the connection is complete. That callback receives two parameters, the second of which is the db object itself. Using the db object, we can get a collection we want to work with. In this case, we save that collection as a variable so that we can work with it throughout the rest of our code more easily. Using the collection variable, we execute a simple insert command and pass the JSON object we want to insert into the database as the first parameter.

The callback function executes after insert accepts two parameters, the second of which is an array of documents affected by the command; in this case, it is an array of documents that we inserted. Once insert is complete and we are inside the callback function, we log some data. You can see that the length of the docs.ops array is 1, as we only inserted a single document. Furthermore, you can see that the single document in the array is the document we inserted, although now it has an extra _id field since MongoDB handles that automatically.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.8.8