Node.js Mongoose-无法使用'findOrCreate'创建超过4个字段`
我使用Node.js、MongoDB和Mongoose,并使用passport.js进行身份验证 以下是我的用户模式:Node.js Mongoose-无法使用'findOrCreate'创建超过4个字段`,node.js,mongodb,mongoose,passport.js,Node.js,Mongodb,Mongoose,Passport.js,我使用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 }); 我的谷歌战略是: p
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
我的结果时,我会看到我的个人资料,以及个人资料照片url和个人资料电子邮件,但我无法看到我的电子邮件id。只创建了4个字段:
\u id
googleId
profilePic
\u v
有人能告诉我如何保存电子邮件字段吗?为什么会出现此问题:
您没有很好地使用
findOrCreate
方法findOrCreate
最多可以使用四个参数。findOrCreate(条件、文档、选项、回调)
:
:用于指定选择过滤器 查找文档条件
[可选]:如果找不到与选择过滤器(doc
)匹配的文档,则此条件
将与您在doc
中拥有的内容合并,然后插入数据库李>条件
[可选]:从插件代码库中,我想您可以使用options
(如果设置为options.upert
)以更新文档 已经存在true
:操作完成后执行的函数李>回调
{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);
}
);
}
)
);
我似乎在mongoose文档中找不到
Model.findOrCreate
方法,您使用的是什么版本的mongoose?我使用的是一个单独的mongoose findOrCreate插件,它将findOrCreate方法添加到模型中。这对于像Passport这样需要它的库很有用。您可以在此处找到其他详细信息: