使用猫鼬在Mongo Atlas中创建一个集合

时间:2020-07-05 13:26:54

标签: javascript node.js mongodb mongoose

我创建了一个新的猫鼬模型名称'users',并创建了一个新的Object 用它来将新记录保存到集合中。

运行代码后,我看不到Mongo Atlas中的任何集合。

我用.once检查到Mongo Atlas的连接,但是之后 运行并获取我无法从Google身份验证获取的个人资料 看到在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()后;和添加箭头功能:

console.log('profile Id',profile.id);
        new User({ googleId: profile.id}).save(err => {
            console.log(err) 
        });

在.save(err =>)中,我在终端中得到空输出。

添加userNewUrlParser后工作并保存到集合中:

mongoose.connect(keys.mongoURI,{ useNewUrlParser: true });

在save(err =>)函数的终端上仍然得到-null

1 个答案:

答案 0 :(得分:0)

保存是您必须调用的函数

        new User({googleId:profile.id}).save(); //create a new instance of a User => and get the profile id , .scae => save to the MongoDB