我创建了一个新的mongoose模型名为'users',并创建了一个新对象,使用它将新记录保存到集合中。
运行代码后,我在Mongo Atlas中看不到任何集合。
我曾经使用。once来检查与Mongo Atlas的连接,但是在运行并从google auth获取我需要的配置文件之后,我看不到任何用Mongo创建的集合,也看不到我创建的对象中的任何记录--使用日志获取一个未定义的记录。
index.js
const express = require('express');
const mongoose = require('mongoose');
const keys = require('./config/keys');
require('./models/User');
require('./services/passport'); //const passportconfig <=
const app = express();
const { Router } = require('express');
mongoose.connect(keys.mongoURI);
const connection = mongoose.connection;
connection.once('open',()=>{
console.log("MongoDB database connection established successfully");
});
require('./routes/authRoutes')(app); //authRoutes using app express
const PORT = process.env.PORT || 5000;
app.listen(PORT);
用户
const mongoose = require('mongoose');
//const { mongoURI } = require('../config/keys');
//const Schema = mongoose.Schema;
const {Schema} = mongoose; //same as line 2 => tell to mongoose object that he have a property called Schema and use it in new object call Schema
const userSchema = new Schema({ //constructor i
googleId: String //user will have googleId for now
});
mongoose.model('users', userSchema);//our new collection User and will follow by the userSchema => only creating collection if it dosent exsits only
护照
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const keys = require('../config/keys');
const mongoose = require('mongoose');
const User = mongoose.model('users');
passport.use(new GoogleStrategy({
clientID: keys.googleClientID,
clientSecret: keys.googleClientSecret,
callbackURL: '/auth/google/callback'
},
(accessToken, refreshToken, profile, done) => {
//console.log('accessToken',accessToken); //allow us to reach to google and show user permissions
//console.log('refreshToken',refreshToken); //allow us to refresh the accessToken
console.log('profile',profile);
new User({googleId:profile.id}).save; //create a new instance of a User => and get the profile id , .scae => save to the MongoDB
console.log(User.googleId);
})
);//passport using new google oauth and handle it
save是一个函数,你必须这样称呼它
new User({googleId:profile.id}).save(); //create a new instance of a User => and get the profile id , .scae => save to the MongoDB