楼主: kychan
9729 63

【2015新书】JavaScript JSON Cookbook   [推广有奖]

61
Reader's 发表于 2017-7-23 00:54:13
  1. Searching for a document in MongoDB with Node.js

  2. Being able to insert documents wouldn't do you much good if you didn't have a way to search for documents. MongoDB lets you specify a template on which to match, and returns objects matching that template.

  3. As with insertions and updates, you'll work with a collection of documents, invoking the collection's find method.

  4. How to do it...

  5. Here's an example that finds all documents in the test collection with a call of kf6gpe-7 and prints them to the console:

  6. var mongo = require('mongodb').MongoClient;

  7. var url = 'mongodb://localhost:27017/test';

  8. mongo.connect(url, function(error, db) {
  9.   console.log("mongo.connect returned " + error);

  10.   var cursor = collection.find({call: 'kf6gpe-7'});
  11.   cursor.toArray(function(error, documents) {
  12.     console.log(documents);

  13.     db.close();
  14.   });
  15. });
复制代码

62
Reader's 发表于 2017-7-23 00:54:47
  1. Updating a document in MongoDB with Node.js

  2. Updating a document in a collection is easy; simply use the collection's update method and pass the data you want to update.

  3. How to do it...

  4. Here's a simple example:

  5. var mongo = require('mongodb').MongoClient;

  6. var url = 'mongodb://localhost:27017/test';

  7. var update = function(collection, callback) {
  8.   collection.update({ call:'kf6gpe-7' },
  9.     { $set: { lat: 39.0, lng: -121.0, another: true } },
  10.     function(error, result) {
  11.       console.log('Updated with error ' + error);
  12.       console.log(result);
  13.       callback(result);
  14.     });
  15. };

  16. mongo.connect(url, function(error, db) {
  17.   console.log("mongo.connect returned " + error);

  18.   // Get the documents collection
  19.   var collection = db.collection('documents');
  20.   update(collection, function(result) {
  21.     db.close();
  22.   });
  23. });
  24. The pattern of this is identical to the insert method; update is an asynchronous method that invokes a callback with an error code and a result.
复制代码

63
钱学森64 发表于 2019-3-7 17:05:33
谢谢分享

64
wangyong8935 在职认证  发表于 2019-10-18 13:58:19
thank you for sharing

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
jg-xs1
拉您进交流群
GMT+8, 2025-12-6 06:47