1. 程式人生 > >nodejs+mongoose 增刪改查

nodejs+mongoose 增刪改查


var mongoose = require('mongoose');
var conn = mongoose.connect('mongodb://10.16.12.95:40000/test');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

//定義壞環url物件
var urlBadLink = new Schema({
id :{ type:String },
host : { type:String },
total : { type:Number },
badCounts : { type:Number },
getRate :{ type:String }

});
mongoose.model('url', urlBadLink);
var URL = mongoose.model("url");

//插入資料
function save(id,host,total,badCounts){
var url = new URL();
url.id = id;
url.host = host;
url.total = total;
url.badCounts = badCounts;
//獲取壞環率
url.getRate = String(Math.round(url.badCounts/url.total*10000)/100)+'%';
url.save();
}

//查詢資料
function showUrls(id){
//URL.find({id:id}).sort({'_id':-1}).limit(5).exec(function(err,docs){
URL.find({id:id}).exec(function(err,docs){
console.log(docs)
})
}
//插入資料
save('004','127.0.0.1',20,1);
//查詢
showUrls('004');

//複雜資料結構舉例
var ExampleSchema = new Schema({
name:String,
binary:Buffer,
living:Boolean,
updated:Date,
age:Number,
mixed:Schema.Types.Mixed,//該混合型別等同於 nested
_id:Schema.Types.ObjectId, //主鍵
_fk:Schema.Types.ObjectId, //外來鍵
array:[],
arrOfString:[String],
arrOfNumber:[Number],
arrOfDate:[Date],
arrOfBuffer:[Buffer],
arrOfBoolean:[Boolean],
arrOfMixed:[Schema.Types.Mixed],
arrOfObjectId:[Schema.Types.ObjectId] ,
nested:{
stuff:String
}
});