使用nodejs操作mongodb來實現增刪改查

2021-06-26 05:52:59 字數 1833 閱讀 1209

本文主要講解使用nodejs操作mongodb,並使用express實現增刪改查

本地環境  win7  nodejs v0.10.29  express 4.9.0  mongodb2.4.10

使用express建立乙個todo的express工程

修改package.json,在dependencies下面新增"mongoose":">= 2.3.1"

我本地修改後的package.json

,

"dependencies":

}

關鍵**tasks.js

var express = require('express');

var router = express.router();

var mongo = require('mongoose');

/* 連線本地mongodb */

mongo.connect("mongodb:",function(err)else

});var schema = mongo.schema,

objectid = schema.objectid;

var task = new schema(

});/*指定 mongodb 文件的type,為新增用 此處新增實際的文件名稱問 db.task2 之前我就混淆了 */

var taskmodel = mongo.model("task2",task);

/*指定 mongodb 文件的type,查詢用 此處查詢實際的文件名稱問 db.task2 */

var taskquery = mongo.model("task2");

/* task首頁,執行了 db.task2.find() 將結果展示在首頁 */

router.get('/', function(req, res) ,function(err,docs));

});});/* 新建task */

router.get('/new', function(req, res) );

});/* 新增task表單提交請求 */

router.post("/add.do",function(req,res)

res.redirect("/tasks") ;

});});/* 編輯,查詢資料並返回到頁面 */

router.get('/edit/:id', function(req, res) );

});});/* 編輯表單提交請求 */

router.post("/edit.do/:id",function(req,res)else

});});

});/* 刪除請求 */

router.get("/delete/:id",function(req,res)else)

} });

});module.exports = router;

效果圖

筆者在剛做新增操作的時候(按照書上的例子),遇到了_id不能為空等等問題,google了半天沒有解決

後來換了這種方式,就解決了。

這個是windows下的mongodb客戶端mongovue 這是最後乙個全功能的不收費的版本。

nodejs中使用monk訪問mongodb

mongodb 安裝mongodb 我覺得還是用mannual install靠譜一點兒 啟動mongodb mongod 連線mogodb mongo writeresult mongo db.products.find pretty 在nodejs中用monk訪問mongodb cd monk ...

mongo簡單操作

use admin 進入資料庫admin db.adduser name pwd 增加或修改使用者密碼 db.system.users.find 檢視使用者列表 db.auth name pwd 使用者認證 db.removeuser name 刪除使用者 show users 檢視所有使用者 sh...

mongo基礎操作

1.linux伺服器中已經安裝了mongo後,在mongo命令下的基礎shell命令 show dbs 顯示資料庫列表 show collections 顯示當前資料庫中的集合 類似關聯式資料庫中的表 show users 顯示使用者 use 切換當前資料庫,這和ms sql裡面的意思一樣 db.h...