zoukankan      html  css  js  c++  java
  • NodeJS加MongoDB应用入门

    OS:Windows 7

    1.下载安装MongoDB:http://www.mongodb.org/downloads

    2.下载安装NodeJS:http://nodejs.org/

    3.运行MongoDB,在cmd窗口运行:C:mongodbinmongod.exe --dbpath C:mongodbdatadb

    4.JavaScript代码例子。

    Copy/Paste以下代码到js文件,例如start.js,放到文件夹c:DebugTest下

    var  mongodb = require('mongodb');
    var  server  = new mongodb.Server('localhost', 27017, {auto_reconnect:true});
    var  db = new mongodb.Db('testdb', server, {safe:true});
    
    db.open(function(err, db){
        if(!err){
            console.log('connect db');
            db.createCollection('testcoll', {safe:true}, function(err, collection){
                if(err){
                    console.log(err);
                }else{
                    
                    var item1 = {name:'Tom', age:"1"};
                       var item2 = {name:'Jerry', age:"2"};
                       collection.insert([item1,item2],{safe:true},function(err,result){
                       console.log(result);
                       }); 
                       collection.find().toArray(function(err,docs){
                       console.log('find');
                       console.log(docs);
                       }); 
                       collection.findOne(function(err,doc){
                        console.log('findOne');
                          console.log(doc);
                       }); 
                }
    
            });
        }else{
            console.log(err);
        }
    });

    5.安装mongodb模块

    打开cmd窗口

    把文件目录切换到start.js文件夹

    运行cmd命令:npm install mongodb

    6.运行start.js

    在cmd窗口运行:node c:debugteststart.js

    窗口输出如下:

    connect db
    [ { name: 'Tom', age: '1', _id: 5300533001a7ec94188eb3df },
      { name: 'Jerry', age: '2', _id: 5300533001a7ec94188eb3e0 } ]
    find
    [ { name: 'Tom', age: '1', _id: 5300533001a7ec94188eb3df },
      { name: 'Jerry', age: '2', _id: 5300533001a7ec94188eb3e0 } ]
    findOne
    { name: 'Tom', age: '1', _id: 5300533001a7ec94188eb3df }

  • 相关阅读:
    Android 自定义标题栏 并进行事件处理
    java synchronized详解
    Java中LinkedList与ArrayList有什么区别
    android动态全屏切换
    java线程机制介绍
    设置导航栏背景和文字属性
    Dictionary的用法
    bundle
    解析Json
    Copy与MutableCopy
  • 原文地址:https://www.cnblogs.com/ldlchina/p/3551334.html
Copyright © 2011-2022 走看看