Mongoose筆記

Mongoose筆記

MONGOOSE

連接

1
2
3
4
5
6
7
8
9
10
11
12
13
var mongoose = require('mongoose');
var options = {
useMongoClient: true,
autoIndex: false, // Don't build indexes
reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0
};

mongoose.connect('mongodb://帳號:密碼@localhost:27017/資料庫名稱',options)
mongoose.Promise = global.Promise; //新版的一些問題

Schema設定

1
2
3
4
5
6
7
8
9
10
11
//設定集合內容與屬性
var userDataSchema = new Schema({
title: {type: String, required: true},
content: String,
author: String
},
{collection: 'user-data'} //設定集合名稱 預設是 UserData加S
);

var UserData = mongoose.model('UserData', userDataSchema); //以mongoose.model方式來宣告並使用

mongoose 搜尋 新增 修改 刪除

搜尋

1
2
3
4
UserData.find()
.then(function(doc){
//do something
})

新增

1
2
3
4
5
6
7
var item = {
titile : 'newtitle',
content: 'someContent',
author: 'someName'
}
var newData = new UserData(item);
newData.save();

修改

1
2
3
4
5
6
7
8
9
10
11
var id = req.body.id;

UserData.findById(id,function(err,doc){
if(err){
console.log('error, no entry found');
}
doc.content = req.body.content;
doc.title = req.body.title;
doc.author = req.body.author;
doc.save();
});

刪除

1
2
3
var id -req.body.id;

UserData.findByIdAndRemove(id),exec();

參閱

MONGOSE文件