我很难用猫鼬做一件简单的事,但是我被卡住了,我不知道为什么。
我遇到此错误Type '{ time: any; value: any; applianceId: any; }' has no properties in common with type 'DeepPartial<Document>'.
在这里您可以找到我的架构:
import * as mongoose from 'mongoose';
const applianceDataSchema = new mongoose.Schema({
applianceId: {type: mongoose.Schema.Types.ObjectId, required: true},
time: {type: Number, required: true},
value: {type: Number, required: true},
});
const ApplianceDataModel = mongoose.model('relationalApplianceData', applianceDataSchema);
export { ApplianceDataModel }
我的插入代码:
const appliance = model.appliances.find(a => a.name == data.appliance); // I find the correct appliance here
const doc = {
time: data.time,
value: data.value,
applianceId: appliance._id // I use the objectId here
};
const applianceDataModel = new ApplianceDataModel(doc); // Error here
我不知道出了什么问题,我想使用objectId对象从数据中引用我的设备。 你能帮我吗?
答案 0 :(得分:0)
此错误的原因是必需的deviceId,并且因为需要等待model.appliances.find(.....)
,所以device._id是未定义的// add async to the callback function for your endpoint
app.post('/your_url', async (req,res)=>{
const appliance = await model.appliances.find(a => a.name == data.appliance);
if(!appliance) res.status(400).send({error:'appliance not found'});
console.log(appliance._id); // should console the _id
const doc = {
time: data.time,
value: data.value,
applianceId: appliance._id
};
const applianceDataModel = new ApplianceDataModel(doc);
await applianceDataModel.save();
res.send({message:'Appliance has been saved'}
});