node.js - Mongoose - 无法使用“findOrCreate”创建超过 4 个字段
问题描述
我正在使用 Node.js、MongoDB 和 Mongoose,并且正在使用 passport.js 进行身份验证。
这是我的用户架构:
const userSchema = new mongoose.Schema({
email: String,
password: String,
googleId: String,
facebookId: String,
profilePic: String,
fName: String,
lName: String
});
还有我的谷歌策略:
passport.use(
new GoogleStrategy(
{
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/dashboard",
profileFields: ["id", "displayName", "photos", "email"]
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
console.log(profile.photos[0].value);
User.findOrCreate(
{ googleId: profile.id },
{ profilePic: profile.photos[0].value },
{ email: profile.emails[0].value },
function(err, user) {
return cb(err, user);
}
);
}
)
);
当我console.log
看到我的结果时,我会看到我的个人资料,以及个人资料照片网址和个人资料电子邮件,但我看不到我的电子邮件 ID。仅创建了 4 个字段:
_id
googleId
profilePic
_v
有人能告诉我如何让电子邮件字段也保存吗?
解决方案
为什么你会遇到这个问题:
你没有findOrCreate
很好地使用这个方法。findOrCreate
最多可以有四个参数。
findOrCreate(conditions, doc, options, callback)
:
conditions
:这用于指定选择过滤器以查找文档。doc
conditions
[可选]:如果未找到与 selection-filter( ) 匹配的文档,则将其与doc
您现有的文档合并,conditions
然后插入数据库。options
[可选]:从插件代码库中,我认为您可以使用options.upsert
(如果设置为true
)更新文档(如果它已经存在)。callback
: 操作完成后执行的函数。
你做错了什么是 passign{ email: profile.emails[0].value }
作为预期的第三个参数options
,你应该将它包含在doc
第二个参数中。
修复
试试这个:
passport.use(
new GoogleStrategy(
{
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/dashboard",
profileFields: ["id", "displayName", "photos", "email"]
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
console.log(profile.photos[0].value);
User.findOrCreate(
{ googleId: profile.id },
// Notice that this function parameter below
// includes both the profilePic and email
{ profilePic: profile.photos[0].value, email: profile.emails[0].value },
function(err, user) {
return cb(err, user);
}
);
}
)
);
推荐阅读
- arduino - 将变量连接到寄存器
- security - 如何在浏览器中的“安全连接”锁定旁边添加测试
- unit-testing - 使用带有服务器回调的 http 进行 Flutter 飞镖测试
- css - 图像大小和鼠标悬停
- python - 如何在按数据透视表 Pandas 分组的列中添加条件
- sql - 如何在联合集运算符的每个 oracle SQL 查询中使用不同的 order by 子句
- bash - 在 \[ 和 \] 之间转义非打印字符的 ANSI 序列
- python - 如何在pygame中按比例将任意整数列表(从最低到最高)放在屏幕上?
- oracle - 在 CLOB 列上创建索引
- cron - Raspberry-pi 在编程重启后不断重启