带有$ elemMatch和更新的猫鼬查询

时间:2019-01-15 13:56:59

标签: mongodb express mongoose

我正在尝试查询一个子文档具有两个与两个值匹配的字段的用户。

用户不能:

  • 更新其他用户的电台。由apiKey验证
  • 使用错误的“ stationName”和“ mac”组合更新工作站

我对上面的规则和下面的架构结构有些混乱。为了遵守上述规则,我不得不多次编写较长的查询。谁能帮我批准我的代码?

猫鼬模型

const stationSchema = new mongoose.Schema({
    mac: String,
    stationName: String,
    syncReadings: Boolean,
    firstReadings: {type: Boolean, default: false},
    latestTemperature: Number,
    latestHumidity: Number,
    temperature: [{
        date: Date,
        reading: {type: Number, default: ""},
        humidity: Number
    }],
    humidity:[{
        date: Date,
        reading: {type: Number, default: ""},
        humidity: Number
    }],
    measures: [{
        date: Date,
        temperature: Number,
        humidity: Number
    }],
    lastUpdated: Date
});

// Define user schema
var userSchema = mongoose.Schema({
   apiKey: String,
   stations : [stationSchema]

},  
{
    usePushEach: true 
}
);

帖子请求中的查询示例

app.post('/api/stations/:stationName/measures', function(req, res, next) {

var now = new Date()

const station = {
    mac: req.body.mac,
    stationName: req.params.stationName,
    measures: {
        date: now,
        temperature: req.body.temperature,
        humidity: req.body.humidity
    }
}

const query = {
    apiKey: req.user.apiKey
}

const elemMatch = {
    stations: { $elemMatch:
        {   'stationName': station.stationName,
            'mac': station.mac
        }
    }
}

const setDoc = { 
    $push: {
        'stations.$.measures': station.measures
    }, 
    $set: { 
        'stations.$.lastUpdated': now,
        'stations.$.syncReadings': true,
        'stations.$.firstReadings': true,
        'stations.$.latestTemperature': station.measures.temperature,
        'stations.$.latestHumidity': station.measures.humidity
    }
}

User.findOne(query, elemMatch)
.exec()
.then(result => {
    console.log(result);
    if(result.stations.length > 0) {
        User.findOneAndUpdate({apiKey: query.apiKey, 'stations.stationName': station.stationName}, setDoc)
        .exec()
        .then(result => {
            res.status(200).send("Updated measures");
        })
        .catch(err =>{
            console.log(err);
            res.status(400).send(err)
        })
    } else if(result.stations.length == 0) {
        res.status(400).send("Station not found!")
    } else {
        res.status(400).send("Some error updating measures")
    }
})
.catch(err =>{
    console.log(err);
    res.status(400).send(err)
})
});

我上面的策略来自无法将查询与$ elemMatch合并然后进行更新。谁能帮助我改善我的代码?

0 个答案:

没有答案