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
    }
});

你可能感兴趣的:(nodejs)