【问题标题】:Mongoose/MongoDB not saving objectsMongoose/MongoDB 不保存对象
【发布时间】:2020-10-17 16:43:49
【问题描述】:

在我的最后一次提交中,我的 POST 路由运行良好,但在开始实施 PassportJS 后,我无法再保存新用户了。我有几次删除数据库和集合,主要是因为我一直在更改模式的结构,所以我想问一下是否有可能发生任何损坏,因为我知道我一直在通过 MongoDB 操作 Mongo指南针。

//DB setup
    mongoose.set('useFindAndModify', true);
    this.connection = mongoose.createConnection(process.env.MONGODB_URL || MONGO_URI, {
        useNewUrlParser: true,
        useCreateIndex: true
    });
    this.connection.once('open', args => console.log('DB is connected'));
    this.connection.once('error', err => console.log(err));

这是路由和路由本身执行的方法。

private async postUser(req: Request, res: Response) {
    const {username, password, email} = req.body;
    console.log(username + " " + password + " " + email);
    const {salt, hash} = this.genPass(password);
    console.log(salt + " " + hash);
    const newUser = new User({ username: username, password: hash, salt: salt, email: email });
    console.log(newUser);
    await newUser.save((err, newUser) => {
        console.log('smth');
        if (err) {
            res.json('username or email already exist');
            return console.error(err);
        }
        else {
            console.log(newUser.get('username') + ' created');
            res.json({data: newUser});
        }
    });
}

this.router.post('/sign', (req: Request, res:Response) => {
        this.postUser(req, res)
            .then(x => console.log (x));
    });

架构

const userSchema = new Schema ({
    username: { type: String, required: true, unique: true},
    password: { type: String, required: true},
    salt: {type: String, required: true},
    email: { type: String, required: true, unique:true, lowercase: true}
},
{
  timestamps: true,
});

export default model('user', userSchema);

控制台输出

(node:19004) 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.

Server on port 3000
DB is connected
admin passw email
cf0bcf9bd942010fba7bfd1bcde96ae93b2e1a55f078a70b1cb48f000551c4e1 
e73a50fb837a55abd9bcc5da1e635cb0c825663aaaf2b3318f8f9bc38ea89e50af2c70f4ee247256a282709b9a6abee0d9ba5
a574d6dec19d519692683027135
{
  _id: 5ef6b7111668ca4a3c0e8332,
  username: 'admin',
  password: 
  'e73a50fb837a55abd9bcc5da1e635cb0c825663aaaf2b3318f8f9bc38ea89e50af2c
   70f4ee247256a282709b9a6abee0d9ba5a574d6dec19d519692683027135',
  salt: 'cf0bcf9bd942010fba7bfd1bcde96ae93b2e1a55f078a70b1cb48f000551c4e1',
  email: 'email'
 }
 undefined
 POST /sign - - ms - -

(也想询问关于弃用警告的问题,但我认为它与本文的主题无关)

【问题讨论】:

    标签: node.js mongodb typescript express mongoose


    【解决方案1】:

    修复它。而不是使用 createConnection() 我使用 mongoose.connect() 并且当我需要对象 Connection 我使用 mongoose.connection。我觉得很奇怪,我很想知道原因,但如果它有效,它就会有效。

    【讨论】:

      【解决方案2】:

      您的用户似乎已保存到数据库中,save 不会返回插入的文档

      await newUser.save((err) => {
              if (err) { 
           ///.... 
          }
      

      您还必须事先检查用户是否存在于数据库中

      User.find({ email: email, (err, user) =>{
           if (err) throw err 
            if(user) return console.log("user already exist")
             //... your code 
          const newUser = new User({ username: username, password: hash, salt: salt, // construct a document
           email: email });
           
           newUser.save()
            
      });
      

      要使 mongoose 已弃用的错误消失,请添加此行

      mongoose.set('useUnifiedTopology', true)
      mongoose.set('useNewUrlParser', true)
      mongoose.set('useFindAndModify', false)
      

      【讨论】:

      • 我在那里使用的语法在实现加密之前就可以工作,而且我一直在检查数据库,所以我确定没有保存任何数据。检查和每个错误管理都打算在回调中发生,所以如果是重复数据的情况,我会像以前一样获得控制台输出。
      猜你喜欢
      • 2017-06-26
      • 2016-11-22
      • 2011-07-01
      • 2021-08-13
      • 2016-12-09
      • 2011-11-20
      • 2019-02-20
      • 2014-11-09
      • 2017-07-27
      相关资源
      最近更新 更多