首页 > 解决方案 > 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 个字段:

有人能告诉我如何让电子邮件字段也保存吗?

标签: node.jsmongodbmongoosepassport.js

解决方案


为什么你会遇到这个问题:
你没有findOrCreate很好地使用这个方法。findOrCreate最多可以有四个参数。
findOrCreate(conditions, doc, options, callback)

  • conditions:这用于指定选择过滤器以查找文档。
  • docconditions[可选]:如果未找到与 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);
        }
      );
    }
  )
);

推荐阅读