Через mqtt я получаю следующее сообщение:
{"7801":{"teste":"teste888"}}
Мне нужно получить информацию и обновить ее в поле teste, например:
colection.update({
"teste":"teste888"
})
Как я могу получить эту информацию прямо из строки в формате JSON?
Мой код:
//mqtt
const mqtt = require('mqtt')
client = mqtt.connect({
host: 'xxx.xxx.xxx.xxx',
port: 1883,
username: 'xxxxxxx',
password: 'xxxxxxxx'
});
// firestore
const admin = require('firebase-admin');
const serviceAccount = require('./firestore/firestoreTeste.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
const db = admin.firestore();
//client mqtt
client.on('connect', () => {
let documents = db.collection('place2').get()
.then(snapshot => {
snapshot.forEach(doc => {
var namePlace = [];
namePlace = doc.id.toString();
client.subscribe(namePlace + "/locker/testex/update")
client.subscribe(namePlace + "/booking/testex/update")
});
});
});
client.on('message', (topic, message) => {
console.info('JSON: ', message.toString());
const namePlace = topic.split("/")[0];
console.info("Name place: ", namePlace);
const nameCol = topic.split("/")[1]
console.info("Name colection: ", nameCol)
const key = message.toString().substr(2,4);
console.info("ID: ", key);
const colection = db.collection("place2").doc(namePlace).collection(nameCol).doc(key);
const teste = JSON.parse(message)
console.info("teste: ", teste)
colection.update({
//teste
})
})
Спасибо!
Я публикую полный код firebase, спасибо
Большой! .. Добро пожаловать .. Когда вы публикуете полный код .. Разработчики могут посмотреть и найти для вас подходящий ответ :)



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Я думаю, вы ищете:
colection.update({
teste: teste["7801"]
})
Это возьмет свойство 7801 из вашего JSON и запишет это значение в поле teste в базе данных.
Если вы не знаете имя поля 7801, вы можете использовать цикл для получения значений из всех свойств верхнего уровня:
let value = "";
Object.keys(teste).forEach((key) => {
value += test[key];
});
colection.update({
teste: value
})
Здесь я просто объединил значения, но вы можете сделать что-то более конкретное для вашего варианта использования.
Дополнительная информация поможет и опубликует полный код Firebase.