Node.js使用Mongoose包操作MongoDB数据库

时间:2023-03-08 15:43:47

1. 安装Mongoose

npm install mongoose

2. 使用

2.1 创建连接

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test');

2.2 获取数据库的一些通知信息

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function(callback){

//do something

});

2.3 创建Schmema和Model

var kittySchema = mongoose.Schema({
             name: String
        });

var Kitten = mongoose.model('Kitten', kittySchema)

var silence = new Kitten({ name: 'Silence' })
        console.log(silence.name); // 'Silence'

2.4 为Model增加“行为”

kittySchema.methods.speak = function () {
            var greeting = this.name
              ? "Meow name is " + this.name
             : "I don't have a name"
            console.log(greeting);
        };

var Kitten = mongoose.model('Kitten', kittySchema);

var fluffy = new Kitten({ name: 'fluffy' });
        fluffy.speak() // "Meow name is fluffy"

2.5 查找

Kitten.find(function (err, kittens) {
            if (err) return console.error(err);
            console.log(kittens)
        });

Kitten.find({ name: /^Fluff/ }, callback)

2.6 保存或者更新

var kitty = new Cat({ name: 'Zildjian' });
        kitty.save(function (err) {
        if (err) // ...
            console.log('meow');
        });

2.7 删除

TaskModel.findById(req.params.id,function(err, task){
            if(!err && task){
                task.remove(function(){
                    res.redirect('/todo/tasks');
                });
            }
            else{
                res.end('not found.')
             }
         })

参考:

1. Mongoose-Getting Started http://mongoosejs.com/docs/index.html

2. Mongoose-docs http://mongoosejs.com/docs/guide.html

3. Queries http://mongoosejs.com/docs/queries.html

附代码:

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Schema = mongoose.Schema; var connStr = 'mongodb://localhost/todo_development'; mongoose.connect(connStr);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
console.log('db open...');
}); var TaskSchema = new Schema({
task: String
});
var TaskModel = mongoose.model('Task', TaskSchema);
console.log('model Task is created.'); /* GET home page. */
router.get('/', function(req, res, next) {
res.render('todo/index', { title: 'To Do List' });
}); router.get('/tasks', function(req, res, next){ //从数据库加载todos
TaskModel.find({}, function(err, docs){
if(!err){
res.render('todo/tasks/index',{
titile: 'Todos index view',
docs:docs
});
}else{
console.log(err);
res.render('todo/tasks/index',{
titile: 'Error happens when load todos.',
docs:[]
});
}
});
}); router.get('/tasks/new', function(req, res, next){
res.render('todo/tasks/new', {
title: 'New Task'
});
}); router.post('/tasks/new', function(req, res){
//save to db
var task = new TaskModel(req.body);
task.save(function(err){
if(!err){
res.redirect('/todo/tasks');
}else{
res.redirect('/todo/tasks/new');
console.log(err);
}
});
}); router.get('/tasks/:id/edit', function(req, res, next){
var task = TaskModel.findById(req.params.id,function(err, task){
if(!err){
res.render('todo/tasks/edit', {
title: 'Edit Task',
task: task
});
}
else{
res.end('not found.')
}
})
}); router.get('/tasks/:id/delete', function(req, res, next){
var task = TaskModel.findById(req.params.id,function(err, task){
if(!err && task){
task.remove(function(){
res.redirect('/todo/tasks');
});
}
else{
res.end('not found.')
}
})
}); router.post('/tasks/edit', function(req, res){
//save to db
var task = new TaskModel(req.body);
task.save(function(err){
if(!err){
res.redirect('/todo/tasks');
}else{
res.redirect('/todo/tasks/' + req.body.id + '/edit');
console.log(err);
}
});
}); module.exports = router;