vendredi 6 mars 2015

How to properly convert this buffer to a json where keys match SchemaTypes for mongoose?

PROBLEM: Mongoose throws an error when trying to pass a Buffer converted to String/json because the "key types" do not match the Mongoose SchemaTypes.


Question: How do I take a string that looks like json {name:'heyhey'} that was converted to a buffer <Buffer 7b 6e 61 6d 65 3a 27 68 65 79 68 65 79 27 7d> and return it back string/json {name:'heyhey'}AND matches the proper SchemaTypes mongoose expects name: String ? Lol wut?


Understanding why: I'm using an Mongoose + MongoDB + MQTTjs.


Starting with my publish script in MQTT:


./publish/index.js



var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://test.mosquitto.org');
client.publish('presence', "{name:'heyhey'}");

client.end();


This works as intended; however, the problems come about when you look at the client.publish() method whereby it converts the message to a buffer via readable-stream , i think?


Now let's look at thing.controller.js which will be subscribed to the presence topic:



var Thing = require('./thing.model');
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://test.mosquitto.org');

client.subscribe('presence');

client.on('message', function (topic, message) {
// message is Buffer
console.log('message buffer', message)
// message buffer <Buffer 7b 6e 61 6d 65 3a 27 68 65 79 68 65 79 27 7d>

var convertMessage = message.toString();
//{name:'heyhey'}
Thing.create(convertMessage, function(err, message) {
console.log(message, "callback message")
if(err) { return handleError(res, err); }
});
});


This Thing.create will through an error



if (obj && '_id' in obj) continue;
^
TypeError: Cannot use 'in' operator to search for '_id' in {name:'heyhey'}


Which is because of the mongoose model is expecting that the name key is a string:



var ThingSchema = new Schema({
name: String,
active: Boolean
});

Aucun commentaire:

Enregistrer un commentaire