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

我创建了一个新的猫鼬模型名称“用户”,并使用它创建了一个新对象以将新记录保存到集合中。


运行代码后,我在 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'

},

更改为 .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


波斯汪
浏览 59回答 1
1回答

慕少森

save 是一个你必须调用它的函数&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new&nbsp;User({googleId:profile.id}).save();&nbsp;//create&nbsp;a&nbsp;new&nbsp;instance&nbsp;of&nbsp;a&nbsp;User&nbsp;=>&nbsp;and&nbsp;get&nbsp;the&nbsp;profile&nbsp;id&nbsp;,&nbsp;.scae&nbsp;=>&nbsp;save&nbsp;to&nbsp;the&nbsp;MongoDB
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript