【问题标题】:Mongoose - Unable to create more than 4 fields using `findOrCreate`Mongoose - 无法使用“findOrCreate”创建超过 4 个字段
【发布时间】:2020-06-09 02:47:50
【问题描述】:

我正在使用 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

谁能告诉我如何保存电子邮件字段?

【问题讨论】:

  • 我在mongoose文档中好像找不到Model.findOrCreate方法,你用的是什么版本的mongoose?
  • 我正在使用一个单独的猫鼬 findOrCreate 插件,它将 findOrCreate 方法添加到模型中。这对于像 Passport 这样需要它的库很有用。您可以在此处找到更多详细信息:npmjs.com/package/mongoose-findorcreate

标签: node.js mongodb mongoose passport.js


【解决方案1】:

您遇到问题的原因:
您没有很好地使用findOrCreate 方法。 findOrCreate 最多可以接受四个参数。
findOrCreate(conditions, doc, options, callback)

  • conditions:这是用来指定选择过滤器的 找到文档。
  • doc[可选]:如果找不到匹配选择过滤器(conditions)的文档,则此doc 与您在conditions 中的内容合并,然后插入到数据库中。
  • options[可选]:从插件代码库,我想你可以使用 options.upsert(如果设置为true) 更新文档,如果它 已经存在。
  • callback:操作完成后执行的函数。

您做错的是将{ 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);
        }
      );
    }
  )
);

【讨论】:

    猜你喜欢
    • 2018-06-01
    • 1970-01-01
    • 2013-02-23
    • 2013-05-24
    • 1970-01-01
    • 2021-06-20
    • 2016-06-16
    • 2014-08-30
    • 2014-12-04
    相关资源
    最近更新 更多