mongodb+express api接口

mongoose.json

{"url":"mongodb://192.168.40.194:35248/cims_db","user":"cims","pass":"cims123$%"}

app.js

var strMongodb = fs.readFileSync('./public/settings/mongodb.json', 'utf-8');
var mongodbSettings = JSON.parse(strMongodb);

mongoose.connect(mongodbSettings.url, {
		 useNewUrlParser:true,
		 useFindAndModify: false,
		 useCreateIndex: true,
		 useUnifiedTopology: true,
		 user: mongodbSettings.user,
		 pass: mongodbSettings.pass
}, function (err) {
	if (err) {
        logger.error('Mongoose.connect Error: ' + err);
   	} else {
   		logger.info('Mongoose.connect return success! ');
   	 }
});

/*** 连接成功*/
mongoose.connection.on('connected', function () {
    logger.info('Mongoose connection open to ' + mongodbSettings.url);
});

/*** 连接异常*/
mongoose.connection.on('error', function (err) {
    logger.error('Mongoose connection error: ' + mongodbSettings.url);
});

/*** 连接断开*/
mongoose.connection.on('disconnected', function () {
   logger.info('Mongoose connection disconnected');
});

models/channels

var mongoose = require('mongoose');
var Schema = mongoose.Schema
var channelSchema = new Schema({
	DId:            { type: Number, required: true, unique: true}, //设备编号,必填,唯一标识
	 SampleName:       { type: String}, //样品名称
	 data:   [{
        samplingPeriod:   { type: Number },//采样周期
        specNum:   { type: Number },//谱图数量 (即时间点数), 仅出现三维数据中,目前设备不支持
        }]
      },{ versionKey: false, collection:'channel' });
var channel = mongoose.model('channel', channelSchema);
module.exports = channel;
//详情
module.exports.channelDetail = function(ChannelId, callback){
    channel.findOne({ChannelId:ChannelId}, callback);
};
//记录数量
module.exports.channelCount = function(condition, callback){
	channel.countDocuments(condition, callback);
};
//分页查询
module.exports.findChannels = function(condition, pageSize, skipCount, callback){
    channel.find( condition, callback).sort( {_id: -1} ).limit(pageSize).skip(skipCount);
};
//单独设置某字段
module.exports.setOnline = function(clientId, online, callback){
    channel.find( condition, callback ).sort( {_id: -1} ).limit(pageSize).skip(skipCount);
};

module.exports.setAuth = function(DId, authData, callback){
	Device.findOneAndUpdate( {DId:DId}, {
        $set:{
        	devUser:authData.devUser,
            devPass:authData.devPPass,
            devAclPublish :authData.devAclPublish,
  }
    }, callback );
};

//add
module.exports.addDevice = function(newDevice, callback){
 newDevice.save(callback);
};
//delete
module.exports.deleteDevice = function(deviceId, callback){
 Device.findOneAndUpdate({DId:deviceId},{$set:{isDel:true,online:false,enabled:false}},{new:true},callback);
};


routes-api-channels

/**
 * 功能:获取通道列表
 * api:get /api/channel/listChannel 
 */
router.get('/listChannel', function(req, res, next) {
	logger.info('API:"get /api/channel/listChannel" accessed.');
	var pageNum =req.query.pageNum ? Number(req.query.pageNum) :
	var pageSize= req.query.pageSize ? Number(req.query.pageSize
	var condition = {};
	Channel.channelCount(condition,function(err,count){
		 if(err){
		 	logger.error("Get device data count error. err="+JSON.string(err));
            return res.status(200).json({code:1,msg:"访问失败,数据库错误!",data:err});
        }
        Channel.findChannels(condition, pageSize, (pageNum-1)*pageSize 	,function(err,list){
            if(err){
            	logger.error("List device data failed.err=" + JSON.stringify(err));
                return res.status(200).json({code:2, msg:"访问失败,数据库错误!",data:err});
            }else{
            logger.info("List device data success.");
                res.status(200).json({code:0, msg:"success",data:{total:countes.status(200).json({code:0, msg:"success",data:{total:count,pageSize:pageSize,totalPage:Math.ceil(count / pageSize), list}});
            }
        });

    });

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值