javascript-Node Express猫鼬数组未填充参考模型

我一直在尝试在模型数组中添加相关模型.但是当我测试api时,数组始终为空.而且我一直在寻找*和google中的答案,但没有任何效果.

SCHEMAS&楷模

let UserSchema = new Schema({
  title: { type: String, required: true },
  firstName: { type: String, required: true },
  lastName: { type: String, required: true },
  username: { type: String, required: true, unique: true },
  avatar: String,
  email: { type: String, required: true },
  dob: String,
  password: { type: String, required: true },
  createdAt: Date,
  accounts: [{ type: Schema.Types.ObjectId, ref: 'Account' }] // --> this is what I want to fill
});

let AccountSchema = new Schema({
  createdAt: Date,
  accountNumber: { type: Number, required: true },
  balance: Number,
  daysLeft: Number,
  nextMonthPayment: Number,
  paymentType: String,
  currentPlan: {
    name: { type: String, required: true },
    usage: {
      used: Number,
      left: Number,
      total: Number,
      meta: {
        trafficData: [{
          date: Date,
          amount: Number,
          download: Number,
          upload: Number
        }],
      }
    }
  },
  user: { type: Schema.Types.ObjectId, ref: 'User' }
});

User = mongoose.model('User', UserSchema);
Account = mongoose.model('Account', AccountSchema);
// end: SCHEMAS & MODELS

处理方式

// POST
router.post('/accounts', (req, res) => {
  user = new User({
    title: 'Ms',
    firstName: 'Paula',
    lastName: 'Testerson',
    username: '@paulatest',
    avatar: '',
    email: 'paula.test@emailtest.com',
    dob: '01 January 1989',
    password: 'test123',
    createdAt: Date.now()
  });

  account = new Account({
    createdAt: Date.now(),
    accountNumber: 7651234,
    balance: 91.75,
    daysLeft: 23,
    nextMonthPayment: 19.57,
    paymentType: 'debit card',
    currentPlan: {
      name: 'Fast Furious',
      usage: {
        used: 10356,
        left: 89644,
        total: 100000,
        meta: {
          trafficData: [{
            date: 'Fri Dec 22 2017 14:42:14 GMT+0000 (GMT)',
            amount: 100.50,
            download: 20.65,
            upload: 16.90
          }],
        }
      }
    },
    user: user._id
  });

  user.save((err) => {
    if (err) { res.send(err); }

    account.save(err => {
      if (err) { res.send(err); }
      res.json({
        message: 'Account created!',
        status: 'created'
      });
    });

    user.find({})
      .populate('accounts') // --> this is not working somehow
      .exec()
      .then((users) => {
        console.log('User - ', users);
      })
      .catch(err => {
        console.log('User err - ', err);
      });
  });
});

// GET
router.get('/', (req, res) => {
  res.json({ message: 'Welcome to accounts api' });
});

router.get('/accounts', (req, res) => {
  Account.find((err, accounts) => {
    if (err) { res.send(err); }
    res.json(accounts);
  });
});

router.get('/users', (req, res) => {
  User.find({})
    .populate('accounts') // --> this is not working somehow
    .exec((err, users) => {
      if (err) { res.send(err); }
      res.json(users);
    });
});

到目前为止,这就是我所做的,但是User.accounts仍然没有填充.有什么解决方案?

解决方法:

问题的解决方案定义如下:

router.post('/accounts', (req, res) => {
    user = new User({
        title: 'Ms',
        firstName: 'Paula',
        lastName: 'Testerson',
        username: '@paulatest',
        avatar: '',
        email: 'paula.test@emailtest.com',
        dob: '01 January 1989',
        password: 'test123',
        createdAt: Date.now()
    });

    account = new Account({
        createdAt: Date.now(),
        accountNumber: 7651234,
        balance: 91.75,
        daysLeft: 23,
        nextMonthPayment: 19.57,
        paymentType: 'debit card',
        currentPlan: {
            name: 'Fast Furious',
            usage: {
                used: 10356,
                left: 89644,
                total: 100000,
                meta: {
                    trafficData: [{
                        date: 'Fri Dec 22 2017 14:42:14 GMT+0000 (GMT)',
                        amount: 100.50,
                        download: 20.65,
                        upload: 16.90
                    }],
                }
            }
        },
        user: user._id
    });

    user.accounts.push(account._id); // you have to pushed the account  id into newly created user doc
    user.save((err, savedUser) => {
        if (err) {
            res.send(err);
        }

        account.save(err => {
            if (err) {
                res.send(err);
            }

            // It is better approach to use populate rather than finding the user by using .find() method
            User.populate(savedUser, {
                path: 'accounts'
            }, (err, populatedUser) => {
                if (err) {
                    res.send(err);
                }
                console.log(populatedUser);

                // send response here //

            });
        });
    });
});

忠告:
最好是建立一种关联,在您的情况下,您是在User模型中引用帐户,而在Account模型中引用用户,这意味着需要双重引用.因此,要处理此问题,您应该引用帐户模型中的用户或引用用户模型中的帐户,而不是两者都引用.

上一篇:javascript-通过MongoDB游标迭代很慢


下一篇:javascript-执行查询时返回未定义的对象