【发布时间】:2021-12-08 00:39:37
【问题描述】:
router.post('/',auth, async (req, res) => {
const { error } = validate(req.body); //Error Check
if (error) return res.status(400).send(error.details[0].message);
let property = new Property({ //Creating Object: Property as per defined Schema:
title: req.body.title,
description: req.body.description,
price: req.body.price,
user: {
_id: req.user._id, //Getting the ID from auth middleware with JWT Token Authenticared
}
});
console.log({property});
await property.save(); //Saving the Object
res.send(property); //Displaying User with created Object i.e. Property
});
我正在使用 POST 方法创建一个属性。
现在我想从 MongoDB 获取数据,但仅限于当前登录并创建该数据的用户。
//Writing a GET METHOD to List of Properties with Valid Token:
router.get('/', async (req,res)=>{
try{
//Getting the Information of User by the current user.id loggin in: ... .select('-password') sets it to don't show password
const property = await Property.findById(req.user );
res.send(property);
}
catch (ex){
console.error(ex.message);
}
});
【问题讨论】:
-
您能否请edit 您的问题显示实际的属性模型架构定义?我认为
user字段是User模型的引用,即{ type: Schema.Types.ObjectId, ref: 'User' }?