使用Mongoose手动填充文档创建时的Mongodb字段

时间:2016-06-16 14:24:25

标签: node.js mongodb mongoose

在Mongoose文档之后,我能够创建两个文档,但是无法用另一个文档填充。

尽管手动设置'account'值以引用其他文档,但我的数据库似乎没有创建关系。

以下是我用过的代码:     

UserAuth.findOne({ email }, (err, user) => {
  if (err) return done(err);

  if (user) {
    return done(null, false,
      { message: 'It appears that email address has already been used to sign up!' });
  }

  // Create the user account
  const newAccount = new UserAccount({
    name: {
      first: req.body.firstName,
      last: req.body.lastName,
    },
  });

  newAccount.save((err) => {
    if (err) throw err;

    // Create the user authentication
    const newAuth = new UserAuth({
      email,
      account: newAccount,
    });

    newAuth.password = newAuth.generateHash(password);

    newAuth.save((err) => {
      if (err) throw err;
      return done(null, newAuth);
    });

    return done(null, newAccount);
  });
});

类别:

用户身份验证

const UserAuthSchema = new Schema({
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  account: {
    type: Schema.Types.ObjectId,
    ref: 'User',
  },
});

module.exports = mongoose.model('UserAuth', UserAuthSchema);

用户帐户

const UserSchema = new Schema({
  name: {
    first: {
      type: String,
      required: true,
    },
    last: {
      type: String,
      required: true,
    },
  },
  team: {
    type: Schema.Types.ObjectId,
    ref: 'Team',
  },
  image: {
    type: String,
    default: 'assets/default_user.png',
  },
});

module.exports = mongoose.model('User', UserSchema);

1 个答案:

答案 0 :(得分:0)

看起来像是部分:

// Create the user authentication
const newAuth = new UserAuth({
  email,
  account: newAccount,
});

应该是:

// Create the user authentication
const newAuth = new UserAuth({
  email,
  account: newAccount._id,
});

然后,当您查询集合时,您必须说明应该填充哪个字段,如(Mongoose文档)[http://mongoosejs.com/docs/populate.html]

中所示

广告请检查2个链接字段的类型是否与文档中提到的相同。