簡體   English   中英

使用Mongoose在文檔創建時手動填充Mongodb字段

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

根據Mongoose文檔,我能夠創建兩個文檔,但是無法在另一個文檔中進行填充。

盡管手動設置了“帳戶”值來引用其他文檔,但我的數據庫似乎並未創建該關系。

以下是我使用的代碼:

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

它看起來像部分:

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

應該:

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

然后,當您查詢集合時,您必須說出應該填充哪個字段,如(貓鼬文檔)中所示[ http://mongoosejs.com/docs/populate.html]

廣告請檢查2個鏈接字段的類型是否與文檔中所述相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM