• nodejs 操作mongodb, 增删改查


    很久没有学node了,之前书看了一半,今天继续学发现版本问题很坑爹,按书例子执行一堆错误。
    想学nodejs操作db,百度半天,一堆sb写神马鸟玩儿?简简单单写一大堆还运行不了的。需要代码也是看别人写的, 还是有必要写个笔记。

    1、安装mongodb、http://www.mongodb.org/,现在出了.msi可以不用命令安装,但是默认安装后在左下角的搜索里搜索不到。
    默认路径在c盘C:\Program Files\MongoDB 2.6 Standard\bin

    2、运行mongodb,首先要把mongo服务启动起来,到mongo的bin目录,可能第一次需要建dbpath(自己指定也可 mongod --dbpath XXXX/data)   ,

    md data
    md data\db

    3、连接mongo
    刚才的窗口别关 ,再打开一个cmd

    默认链接到test库 (不知道说法对不对,暂时我把它理解为库)
    show collections   列出所有表(所有集合)



    4、mongodb命令略过不说

    5、nodejs操作mongodb
    新建一个目录  例如叫mongo, 打开node  ,cd mongo目录
    npm install mongodb    安装mongodb驱动
    逐个注释去掉单独运行然后查询效果吧,
    db.mycoll.find()       我表名叫mycoll

    var mongodb = require('mongodb');
    var server = new mongodb.Server('localhost', 27017, {auto_reconnect: true});
    var db = new mongodb.Db('test', server, {safe: true});  //test是上面截图连接的库
    
    db.open(function (err, db) {
        if (!err) {
            console.log('connect');
    
            //增 ,mycoll是查询的表 ,貌似别人叫合集
    //        db.collection('mycoll', {safe: true}, function (err, collection) {
    //            var tmp1 = {title: 'hello', number: 1};
    //            collection.insert(tmp1, {safe: true}, function (err, result) {
    //                console.log(result);
    //            });
    //        });
    
            //
    //        db.collection('mycoll', {safe: true}, function (err, collection) {
    //            collection.remove({title: 'hello'}, {safe: true}, function (err, result) {
    //                console.log(result);
    //            });
    //        });
    
            //
    //        db.collection('mycoll', {safe: true}, function (err, collection) {
    //            collection.update({title: 'hello'}, {$set: {number: 3}}, {safe: true}, function (err, result) {
    //                console.log(result);
    //            });
    //        });
    
            //
    //        db.collection('mycoll', {safe: true}, function (err, collection) {
    //            var tmp1 = {title: 'hello'};
    //            var tmp2 = {title: 'world'};
    //            collection.insert([tmp1, tmp2], {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);
        }
    });



  • 相关阅读:
    通过Internet使用VSS2005
    基于角色的权限设计(一)
    WFF架构及技术
    WFF概述
    企业库:Cache
    权限设计(二)
    应用系统中的编码和编码规则
    希望更多的人也可以来应用wordpress程序
    说说我的一点小感受了
    思维决定命运
  • 原文地址:https://www.cnblogs.com/skyweaver/p/4149693.html
Copyright © 2020-2023  润新知