我的模特
const mongoose = require('mongoose');
const TelemetrySchema = new mongoose.Schema({
MQTT: {
Id: { type: String, trim: true, required: true },
},
Presets: [{
Id: Number,
Message: String,
}],
});
module.exports = mongoose.model('Telemetry', TelemetrySchema);
我想做的是:
如果具有指定ID的对象已存在,则覆盖它.如果对象尚不存在,则使用指定ID创建一个新对象.
我收到了一个Preset
个对象,以及模型中的预设应该是什么样子:
T=0:{Id: 1, Message: 'A'}
->;[{Id: 1, Message: 'A'}]
T=1:{Id: 2, Message: 'B'}
->;[{Id: 1, Message: 'A'}, {Id: 2, Message: 'B'}]
T=3:{Id: 1, Message: 'Z'}
->;[{Id: 1, Message: 'Z'}, {Id: 2, Message: 'B'}]
有没有可能只用一个findOneAndUpdate
?我有个可行的办法但我不喜欢...
client.on('message', async (topic, payload) => {
const s = payload.toString();
const p = JSON.parse(s);
const id = topic.split('/');
const existingTelemetry = await Telemetry.findOne({
'MQTT.Id': id[1],
'Presets.Id': p.Id,
});
if (existingTelemetry) {
// If an object with the same id exists, update the existing object
await Telemetry.findOneAndUpdate(
{
'MQTT.Id': id[1],
'Presets.Id': p.Id,
},
{
$set: {
'Presets.$': p,
},
},
{
new: true,
omitUndefined: true,
},
);
} else {
// If no object with the same id exists, add the new object
await Telemetry.findOneAndUpdate(
{
'MQTT.Id': id[1],
},
{
$addToSet: {
Presets: p,
},
},
{
upsert: true,
new: true,
omitUndefined: true,
},
);
}
});