【问题标题】:Node.js - mongoose model.save() isn't saving data to my collectionNode.js - mongoose model.save() 没有将数据保存到我的集合中
【发布时间】:2020-07-06 04:31:23
【问题描述】:

注册时,我的用户没有保存到数据库中。有谁知道这里出了什么问题?

架构+模型:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/testusers', {useNewUrlParser: true});
const Schema = mongoose.Schema;

let userSchema = new Schema({
  steamId: String,
  username: String,
  avatar: String,
  tradelink: String,
  balance: Number,
});


let userModel = mongoose.model('User', userSchema); 

查找并保存:

userModel.findOne({ steamId: profile.id } , (err,user) => {
      if(!user) {
        let newUser = new userModel({steamId:profile._json.steamid, username: profile._json.personaname,avatar: profile._json.avatar, tradelink: '', balance:0});
        console.log(newUser);
        newUser.save((err,user) =>{
          console.log(err);
          console.log('created user');
          return done(err,user);
        }); 
      }
      else {
        console.log('user exists');  

        return done(err,user);
      }
    });

采集数据(保存后为空):https://prnt.sc/rmlsc2

控制台输出:

PS C:****> node app.js
(node:26628) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
{
  _id: 5e7b78aae3903a680486cb13,
  steamId: '76561198126366365',
  username: 'BaeWolfy',
  avatar: 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d3/d36a7d04988b8730a0a75516a7dbfa24ee1a45fc.jpg',
  tradelink: '',
  balance: 0
}
null
created user

【问题讨论】:

  • 您好,您的代码似乎正确。我只能说明为什么会发生这种情况:当与 mongo 的连接未正确完成时,但您的连接似乎是正确的。如果连接不成功,Mongoose 不会在默认模型上说任何内容,并尝试保存文档。
  • 你可以试试这个mongoose.connect('mongodb:mongodb://localhost/testusers', {useNewUrlParser: true});
  • Console 说它已连接,但我很确定它之前也已连接,即使没有添加代码,因为我已经打开了与我的 atlas 集群的连接。添加的代码仍然不能很好地保存。
  • 阿特拉斯集群???您正在连接到本地主机。我错过了什么吗?
  • 对不起,我犯了一个愚蠢的错误,非常抱歉浪费您的时间我是新手,出于某种原因,我认为使用 mongodb 社区指南针并连接到集群充当本地主机,但在意识到我的错误后它确实没有,我输入了 atlas 集群连接字符串,它现在正在工作。感谢您帮助我意识到并再次为浪费时间感到抱歉

标签: node.js mongodb mongoose passport.js


【解决方案1】:

在连接字符串中犯了一个愚蠢的错误,我使用 localhost 而不是我的 atlas 集群连接字符串。它现在正在工作。

【讨论】:

  • 你能补充一下问题吗?您必须更改的代码?
  • 我使用的是mongoose.connect('mongodb://localhost:27017/testusers', {useNewUrlParser: true});,但我需要连接到我的 atlas 集群的字符串:mongoose.connect('mongodb+srv://<USER>:<PASSWORD>@cluster0-s4jtr.gcp.mongodb.net/testusers', {useNewUrlParser: true}); 用户和密码当然是占位符,因为我不想分享这些..
猜你喜欢
  • 1970-01-01
  • 2020-01-19
  • 2013-02-13
  • 2017-10-08
  • 1970-01-01
  • 2016-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多