简体   繁体   English

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

[英]Manually populating Mongodb field on document creation with Mongoose

Following the Mongoose documentation, I was able to create two docs, but am unable to populate one with the other. 根据Mongoose文档,我能够创建两个文档,但是无法在另一个文档中进行填充。

Despite manually setting the 'account' value to reference the other document, my database doesn't seem to create the relation. 尽管手动设置了“帐户”值来引用其他文档,但我的数据库似乎并未创建该关系。

Below is the code I've used: 以下是我使用的代码:

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);
  });
});

Collections: 集合:

User Auth 用户认证

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);

User Account 用户帐号

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);

It looks like the part: 它看起来像部分:

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

should be: 应该:

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

And then, when you query the collection, you have to say which field should be populate, as shown in (Mongoose documentation)[ http://mongoosejs.com/docs/populate.html] 然后,当您查询集合时,您必须说出应该填充哪个字段,如(猫鼬文档)中所示[ http://mongoosejs.com/docs/populate.html]

Ad please check that the types of the 2 linked fields are the same as mentioned in the documentation. 广告请检查2个链接字段的类型是否与文档中所述相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM