nodejs / mongoose:我的链接.then()调用有什么问题

时间:2018-03-10 18:43:22

标签: node.js mongodb mongoose

我的代码正在尝试:

  1. 创建User模型
  2. 的实例
  3. 使用与新创建的用户相同的电子邮件地址在Subscriber模型中查找实例
  4. 将新用户的subscribedAccount媒体资源与Subscriber
  5. 上的findOne查询找到的user.email实例相关联

    代码:

    // Check that I have a subscriber with email 'test@test.com'
    Subscriber.findOne({email:'test@test.com'})
              .then(d => console.log(`\nResult of check for a subscriber with email test@test.com:\n ${d}`));
    
    User.create({name: {first: 'test first', last: 'test last'}, email: 'test@test.com', password: 'pass123'})
    .then(u => {
      user = u;
      // Check that user.email contains 'test@test.com'
      console.log(`\nCreated user's email address: ${user.email}\n`);
      Subscriber.findOne({email: user.email});
    })
    .then(s => {
      console.log(`\nAnything found by findOne and passed to this .then()?: ${s}`);
      user.subscribedAccount = s;
      user.save();
    })
    .catch(e => console.log(e.message));
    

    控制台结果:

      

    http://localhost:3000运行的服务器已成功连接   猫鼬!

         

    通过电子邮件test@test.com检查订户的结果:
      {组:   [],_ id:5aa422736518f30fbc0f77e2,姓名:'测试名称',电子邮件:   ' test@test.com' ;,zipCode:11111,__ v:0}

         

    创建用户的电子邮件地址:test@test.com

         

    findOne发现并传递给此.then()?:undefined

    为什么Subscriber.findOne会返回undefined?这是实际发生的事情还是我失踪的其他事情?

    以下是UserSubscriber的模型定义。如果您需要从应用程序中查看其他内容以告知发生了什么,请告诉我。

    User

    const mongoose = require('mongoose');
    const {Schema} = require('mongoose');
    
    var userSchema = new Schema( {
      name: {
        first: {
          type: String,
          trim: true
        },
        last: {
          type: String,
          trim: true
        }
      },
      email: {
        type: String,
        required: true,
        lowercase: true,
        unique: true
      },
      zipCode: {
        type: Number,
        min: [ 10000, 'Zip code too short' ],
        max: 99999
      },
      password: {
        type: String,
        required: true
      },
      courses: [ {
        type: Schema.Types.ObjectId,
        ref: 'Course'
      } ],
      subscribedAccount: {
        type: Schema.Types.ObjectId,
        ref: 'Subscriber'
      }
    }, {
      timestamps: true
    } );
    
    userSchema.virtual('fullName').get(function() {
      return `${this.name.first} ${this.name.last}`;
    
    });
    module.exports = mongoose.model('User', userSchema);
    

    Subscriber

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    let subscriberSchema = new Schema({
      name: {
        type: String,
        required: true
      },
      email: {
        type: String,
        required: true,
        lowercase: true,
        unique: true
      },
      zipCode: {
        type: Number,
        min: [10000, 'Zip Code too short'],
        max: 99999
      },
      groups: [{type: Schema.Types.ObjectId, ref: 'Group'}]
    });
    
    subscriberSchema.methods.getInfo = function() {
      return `Name: ${this.name} Email: ${this.email} Zip Code: ${this.zipCode}`;
    }
    subscriberSchema.methods.findLocalSubscribers = function() {
      return this.model('Subscriber')
                 .find({zipCode: this.zipCode})
                 .exec();
    }
    
    //model.exports = mongoose.model('Subcriber', subscriberSchema);
    
    var Subscriber = exports.Subscriber = mongoose.model('Subscriber', subscriberSchema);
    

1 个答案:

答案 0 :(得分:1)

你应该这样做

// Check that I have a subscriber with email 'test@test.com'
    Subscriber.findOne({email:'test@test.com'})
              .then(d => console.log(`\nResult of check for a subscriber with email test@test.com:\n ${d}`));

    User.create({name: {first: 'test first', last: 'test last'}, email: 'test@test.com', password: 'pass123'})
    .then(u => {
      user = u;
      // Check that user.email contains 'test@test.com'
      console.log(`\nCreated user's email address: ${user.email}\n`);
      Subscriber.findOne({email: user.email});


      console.log(`\nAnything found by findOne and passed to this .then()?: ${s}`);
      user.subscribedAccount = s;
      user.save()
      .then(s => {
            //user has been updated
        })
      .catch(err => {
         res.status(err).json(err);
         })

      })
       })
     . catch(e => console.log(e.message));