Hour 21. Working with MongoDB Data in Node.js Applications


What You’ll Learn in This Hour:

Image Inserting new documents into a collection from Node.js

Image Removing documents from a collection in Node.js

Image Getting, manipulating, and saving a single document in a collection from Node.js

Image Updating documents in a collection from Node.js

Image Performing an upsert operation from Node.js


Continuing from the last hour, this hour describes the Node.js MongoDB driver and shows how to implement it to add, manipulate, and remove documents from a collection in your Node.js applications. Several methods are available for changing data in a collection. You can insert new documents, update existing documents using update or save, remove old documents, and apply an upsert (which first tries to update documents and, if it finds none, then inserts a new one).

The following sections cover the various methods on the Node.js Collection object that enable you to manipulate data in the collection. You see how to insert, delete, save, and update documents in a collection from your Node.js application.

Adding Documents from Node.js

An important task when interacting with MongoDB databases from Node.js is inserting documents into collections. To insert a document, you need to first create a JavaScript object that represents the document that you want to store. Insert operations pass the JavaScript object to the MongoDB sever as a BSON that you can insert into the collections.

When you have a JavaScript object version of your new document, you can store it in the MongoDB database using the insert() method on an instance of the Collection object that is connected to the database. The following shows the syntax for the insert() method, where the doc parameter can be a single document object:

insert(doc, callback)

For example, the following shows an example of inserting a single document and an array of documents into a collection:

var doc1 = {'name' : 'Fred'};
myColl.insert(doc1, function(err, results){
  . . .
});

To insert multiple documents into your collection, you can pass an array of JavaScript objects to the insert() method on the Collection object. For example:

var doc2 = {'name' : 'George'};
var doc3 = {'name' : 'Ron'};
myColl.batchInsert([doc2, doc3], function(err, results){
 . . .
});

The insert() method returns the newly created documents as JavaScript objects. These objects contain the new _id value generated by the server.

Removing Documents from Node.js

You will need to delete documents from your MongoDB collection from Node.js to keep space consumption down, improve performance, and keep things clean. The remove() method on Collection objects makes it simple to delete documents from a collection. The syntax for the remove() method follows:

remove([query], callback)

The query parameter is a JavaScript object that identifies which document(s) you want to delete. The request matches the fields and values in the query with the fields and values of the object, and only those that match the query are updated. If no query is provided, all the documents in the collection are deleted.

For example, to delete all documents in the words_stats collection, you would use

collection.remove(function(err, results){
  . . .
});

The following code deletes all words that start with a from the words_stats collection:

var query = {'first' : 'a'};
collection.remove(query, function(err, results){
  . . .
});

The remove() method returns a count of the documents deleted as the second parameter to the callback function.

Saving Documents from Node.js

A convenient method of updating objects in the database is to use the save() method on Collection objects. The save method accepts a JavaScript object as a parameter and saves it to the database. If the document already exists in the database, it is updated with the new values. If the document does not already exist in the database, a new document is created.

The following shows the syntax of the save() method, where the doc parameter is the JavaScript object representing the document to be saved to the collection:

save(doc, callback)

The save() method returns a count of the documents saved as the second parameter to the callback function.

Updating Documents from Node.js

After objects have been inserted into a collection, you often need to update them from Node.js as data changes. The update() method on the Collection object enables you to update documents in a collection. The update method is versatile yet fairly easy to implement. The following shows the syntax for the update() method:

update(query, update, [options], callback)

The query parameter is a JavaScript object that identifies which document(s) you want to change. The request matches the properties and values in the query with the fields and values of the object, and only those that match the query are updated. The update parameter is a JavaScript object that specifies the changes to make to the documents that match the query. Hour 8, “Manipulating MongoDB Documents in a Collection,” describes the update operators used in this object.

The options parameter enables you to set specific options for write concern and for update operations. For update() operations, you need to be aware of the upsert and multi parameters. The upsert parameter is a Boolean that determines whether an upsert operation should be done; if it is true and no documents match the query, a new document is inserted into the collection. The multi parameter is also a Boolean. When true, the update operation is applied to all documents that match the query; otherwise, only the first document is updated.

For example, the following changes the category field value to old for items in the collection for which category currently is new. With upsert set to false, new documents are not created even if no documents have a category of new. With multi set to true, all documents that match are updated:

var query = {'category' : 'New'};
var update = {'$set' : {'category' : 'Old'}};
var options = {'upsert': false, 'multi': true};
myColl.update(query, update, options, function(err, results){
. . .
});

The update() method returns a count of the documents saved as the second parameter to the callback function.

Upserting Documents from Node.js

Another way to use the update() method on the Collection object in Node.js is to use an upsert operation. An upsert operation first tries to update documents in the collection. If no documents match the update query, the $set operator creates a new document and adds it to the collection. The following shows the syntax for the update() method:

update(query, update, [options], callback)

The query parameter identifies which document(s) you want to change. The update parameter is a JavaScript object that specifies the changes to make to the documents that match the query. For upsert operations, the upsert option should be set to true and the multi option should be set to false.

For example, the following performs an upsert on a document with name=myDoc. The $set operator defines the fields used to create or update the document. With upsert set to true, if the document is not found, it is created; otherwise, it is updated.

var query = {'name': 'myDoc'};
var setOp = {'name': 'myDoc',
             'number', 5,
             'score', 10};
var update = {'$set': setOp};
var options = {'upsert': true, 'multi': false};
update(query, update, options, function(err, results){
  . . .
});

Summary

In this hour, you used the Node.js MongoDB driver to add, manipulate, and remove documents from a collection in your Node.js applications. You used several different methods on the Collection object to change data in a collection.

The insert() method adds new documents. The remove() method deletes documents. The save() method updates a single document.

You can use the update() method in multiple ways. You can have it update a single document or multiple documents. You can also apply the upsert option to insert new documents into the collection if none matches.

Q&A

Q. Is it possible to read documents from the cursor as a Node.js-readable stream?

A. Yes. The Node.js MongoDB driver provides the CursorStream() class, which converts a Cursor object into a readable stream object.

Workshop

The workshop consists of a set of questions and answers designed to solidify your understanding of the material covered in this hour. Try answering the questions before looking at the answers.

Quiz

1. Which operation do you use from a Node.js application to create a new document if one does not exist?

2. How do you limit the update() method to only a single document?

3. True or false: You can use the save() method on Collection objects only to save existing documents.

4. What type of parameter defines the fields to update in the update() method of the Collection object?

Quiz Answers

1. Use the update() method on the Collection object with upsert set to true.

2. Set the multi parameter to false.

3. False. save() adds the document if it doesn’t exist.

4. It is a JavaScript object that contains MongoDB update operators as fields.

Exercises

1. Find a new word that you want to add to the word_stats collection in the example dataset. Write a new Node.js application similar to the Node.jsDocAdd.js file to add that word.

2. Create a new Node.js application that uses the update() method to update all words with first letter of e and add the category of eWords to them.

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

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