Node/Mongoose -创建模型并传入登录的用户详细信息,而不需要电子邮件/密码



刚接触猫鼬,希望有人能帮我弄清楚一些事情。我正在尝试创建一个投票应用程序,用户可以创建投票。

我已经实现了登录,所以用户被保存在标题下的'req。,在我的民意调查中,我想保存创建民意调查的用户,但我只想保存id和名称。我不想要密码和电子邮件等。

轮询模式

const pollSchema = new Schema({
question: String,
options: [optionsSchema],
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User'},
voted: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }]
});

从头文件

获取登录用户
const userId = await req.user;
const user = await User.findById(userId);

console.log(用户)=

{
polls: [],
_id: xxxxxxxx,
name: 'Joe Bloggs',
email: 'joeblogg@gmail.com',
password: 'xxxxxxxx',
__v: 0
}

我不想传递密码或电子邮件,我只想传递ID和名称给投票模型,像这样:

const poll = await Poll.create({
question,
user: {
_id: user.id,
name: user.name
},
options: options.map(option => ({
option,
votes: 0
})),
});

两个问题:

第一个是传递'id'而不是'_id'导致此错误:

'Poll validation failed: user: Cast to ObjectId failed for value'

这让我很困惑,我以为猫鼬会识别'id'和'_id'相同。

如果我更改为'_id',它再次工作,但Postman输出是。

user: xxxxxxxxxxxxx (id)

返回id,但不返回我添加的名称

name: user.name

创建民意调查对象时,您应该只添加用户的对象id(而不是id和名称)以及其他民意调查数据。

const poll = await Poll.create({
question,
user: ObjectId(user._id),
options: options.map(option => ({
option,
votes: 0
})),
});

检索可以使用的Poll数据时,

const poll = await Poll.find().populate('user', '_id', 'name');

裁判:https://mongoosejs.com/docs/populate.html字段选择

最新更新