如何开始编写简单的Nodejs和基于Mongoose的应用程序?这是简单的TCP服务器:
var net = require('net');
var server = net.createServer(function (socket) {
socket.on('data', function(data){
//here I want to save data.toString() in a simple db
//db is yet not created, shld I create it first manually?
//data format is {_id : 'automatically generated', rawValue: 'data.toString()'}
});
});
server.listen(1337, "127.0.0.1");
答案 0 :(得分:2)
如果您使用的是猫鼬,它将类似于以下内容:
var sys = require('util')
, mongoose = require('mongoose');
//setup mongose
mongoose.connect('mongodb://localhost/test');
Schema = mongoose.Schema;
var DataSchema = new Schema({
rawValue: String
});
mongoose.model('data', DataSchema);
var net = require('net');
var server = net.createServer(function (socket) {
socket.on('data', function(data){
var Data = mongoose.model('data');
var object = new Data();
object.rawValue = data;
object.save();
console.log('Saved object');
});
});
server.listen(1337, "127.0.0.1");