How to add a datetime field to Mongodb at Node.js program

July 24, 2018 at 06:54:54
Specs: Windows 7, i5 2520M / 8 GB
This is my first time to write a Node.js program. I need to write a document(record) to Mongodb and one field is datetime(format 'YYYY-MM-DD HH:mm:ss.SSS'). but get some syntax error at line 24(mongoose.Schema). How can I modify this program?

Please assist me, thanks!!!

Program as below:


var moment = require('moment');
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost/NO4');
console.log("db connect");

Prev_X = 0;
Prev_Y = 0;
Prev_Z = 0;
VR = 0;


var date = require('date-and-time');
var collectionName = 'NO4';
var catSchema = mongoose.Schema(
{
RP: Number,
GX: Number,
Acc_X: Number,
Acc_Y: Number,
Acc_Z: Number//,
//Dtime: datetime //date //{ type: Date, default: Date.now }// default date
},{ versionKey: '_somethingElse' });
var Cat = mongoose.model('Cat',catSchema,collectionName);

var SerialPort = require('serialport');
var express = require('express');
var bodyParser = require('body-parser'); //used for handling POST Data Parser
var app = express();


app.use('/www', express.static(__dirname + '/public')); //used for static file(html,jpg,txt,...)
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

const Readline = SerialPort.parsers.Readline;
var port = new SerialPort('COM4',
{baudRate: 115200,
parser: new SerialPort.parsers.Readline('\n')
});



// Read the port data
var sensor={"RP":0,"GX":0,"Dtime":"2018-07-31 00:00:000"}
var Tsensor={"Acc_X":0,"Acc_Y":0,"Acc_Z":0}


port.open(function (err) {
if (err) {
port.close
return console.log('Error opening port: ', err.message);
}

// Because there's no callback to write, write errors will be emitted on the port:
//port.write('main screen turn on');
});

port.on('open', function() {
// open logic

s=''
port.on('data', function (data) {

//console.log(data);
s+=data

s=s.trim();
.
.
.
.
add();
s=''

});

// Read data that is available but keep the stream from entering "flowing mode"

})


app.get('/sensor', function(req, res) {

res.writeHead(200, {'Content-Type': 'application/json',"Access-Control-Allow-Origin":"*"});
var json=JSON.stringify(sensor);
console.log("end",json);
res.end(json);

});


app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});

function add() {

var Rdata = new Cat();
Rdata.RP = sensor.RP;
Rdata.GX = sensor.GX;
Rdata.Acc_X = Tsensor.Acc_X;
Rdata.Acc_Y = Tsensor.Acc_Y;
Rdata.Acc_Z = Tsensor.Acc_Z;
var Dtime=moment().format('YYYY-MM-DD HH:mm:ss.SSS');
Rdata.Dtime = Dtime;

//存入該資料到MongoDB
Rdata.save(function (err) {

if (err) {
// 存入失敗
console.log('Something\'s wrong');
return;
}

// 存入成功
// console.log('Add successfully! ');
//process.exit();
});

}


See More: How to add a datetime field to Mongodb at Node.js program

Reply ↓  Report •
Related Solutions


Ask Question