有關數據庫的有用的一些 api,即是mongoose. 在node開發中,底層去處理更多的細節。加快開發速度,維護更少的代碼。node
啓動mongodb服務器,創建mongodb鏈接mongodb
npm install mongoose
複製代碼
var mongoose = require('mongoose')
// 鏈接tasks的數據庫
var db = mongoose.connect('mongodb://localhost/tasks')
// 註冊schmea,使用mongoose去管理數據時,須要註冊schema
var Schema = mongoose.Schema
var Tasks = new Schema({
project: String,
description: String
})
// 經過訪問schma,去帶動mongoose工做
mongoose.model('Task', Tasks)
var Task = mongoose.model('Task')
var task = new Task()
能夠直接省略爲一句話
var task = mongoose.model('Task', Tasks)
複製代碼
一項:
task.project = 'bikeshed'
task.description = 'do you know the mongoose'
task.save(function(err) {
if (err) throw err;
console.log('task saved')
})
// save 只能夠保存 單項
//且 var task = new Task() 不可少
多項任務:
var taskArr = [{project: '00', description: '00'}, {project: '11', description: '11'}]
/// 保存
task.collection.insert(taskArr, onInsert)
function onInsert(err, taskArr) {
if (err) throw err;
console.log('task saved array')
}
or
task.create(taskArr, function(err, small) {
if (err) throw err;
console.log('task saved array create')
})
複製代碼
var Task = mongoose.model('Task', Tasks)
Task.find({'project':'00'}, function(err, tasks) {
for (var i = 0; i < tasks.length; i++) {
console.log('id' + tasks[i]._id);
console.log(tasks[i].description)
}
})
複製代碼
var Task = mongoose.model('Task', Tasks)
// 根據id去找該項記錄, 修改description
Task.update({_id: 'XXXX'}, {description: 'XXX'}, {multi: false})
複製代碼
var Task = mongoose.model('Task');
Task.findById('XXXXXX', function(err, task) {
task.remove()
})
複製代碼