为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

波斯汪 2022-11-03 15:17:59
我创建了一个新的猫鼬模型名称“用户”,并使用它创建了一个新对象以将新记录保存到集合中。运行代码后,我在 Mongo Atlas 中看不到任何集合。我使用 .once 检查与 Mongo Atlas 的连接,但在运行并从 google auth 获取我需要的配置文件后,我看不到在 Mongo 中制作的任何集合,也看不到我创建的对象中的任何记录 - 使用未定义一个日志。index.jsconst 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 expressconst 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 Schemaconst 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
查看完整描述

1 回答

?
慕少森

TA贡献2019条经验 获得超9个赞

save 是一个你必须调用它的函数

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



查看完整回答
反对 回复 2022-11-03
  • 1 回答
  • 0 关注
  • 58 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信