谁能帮我解决这个问题。我不知道什么是真正的问题与我的 req.user.id
. 其实我是新来的mongoose。
这是我的 contact.js
档案
router.post(
'/',
[auth, [check('name', 'name is required').not().isEmpty()]],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, email, phone, type } = req.body;
try {
const newContact = new Contact({
name,
email,
phone,
type,
user: req.user.id,
});
console.log("dfdwfwefwe ",req.user.id)
const contact = await newContact.save();
res.json(contact);
} catch (err) {
console.error(err.message);
res.status(500).send('Server errors');
}
}
);
可能在你的contact schema中,你使用了
name: {
type: mongoose.Schema.Types.ObjectId
}
你要把它改成
name: {
type: String
}
因为 "sara smith"
是 String
,不 ObjectId
. 这就是为什么你的验证失败