簡體   English   中英

在 ZCCADCDEDB567ABAE643E15DCF0974E503Z 中引用另一個 Schema

[英]Reference another Schema in Mongoose

所以我必須架構。 PostSchema 和 UserSchema

const mongoose = require("mongoose")

const PostSchema = new mongoose.Schema({
    content: {
        type: String,
        required: true,
    },
    likes: {
        type: Number,
        required: true
    },
    rescreams: {
        type: Number,
        required: true
    },
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
})

module.exports = mongoose.model("Post", PostSchema)

用戶架構:

const bcrypt = require("bcrypt");
const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
  userName: { type: String, unique: true },
  email: { type: String, unique: true },
  password: String,
});

// Password hash middleware.

UserSchema.pre("save", function save(next) {
  const user = this;
  if (!user.isModified("password")) {
    return next();
  }
  bcrypt.genSalt(10, (err, salt) => {
    if (err) {
      return next(err);
    }
    bcrypt.hash(user.password, salt, (err, hash) => {
      if (err) {
        return next(err);
      }
      user.password = hash;
      next();
    });
  });
});

// Helper method for validating user's password.

UserSchema.methods.comparePassword = function comparePassword(
  candidatePassword,
  cb
) {
  bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
    cb(err, isMatch);
  });
};

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

我的問題是:我正在嘗試在 Post Schema 中引用 User Object ID。 如您所見,我已使用類型:mongoose.Schema.Types.ObjectID 完成此操作。 我已經多次看到這一點。 但在我的數據庫中,用戶從未出現在文檔中。 我需要做什么?

干杯

引用文檔和嵌入文檔是有區別的。

如果要將文檔存儲在文檔中,則應將其嵌入,因此讀取操作會更快,因為您不需要執行 JOIN 操作。

而引用意味着存儲您正在引用的實體的 ID,當您需要訪問您正在引用的文檔時,您需要通過您存儲的 ID 從集合中獲取它。 它比嵌入慢,但它為您提供更高的一致性和數據完整性,因為數據在集合中存儲一次,並且不會在每個 object 處重復。 並且 MongoDB 不支持外鍵,所以你應該小心引用。

因此,當您使用ref存儲文檔時,您需要將ObjectID作為user ,然后獲取您需要添加populate調用的文檔。 例如

PostShema.findOne({ _id: SomeId }).populate('user');

嘗試保存在變量中:

 const UserId = UserSchema.Schema.Types.ObjectId;

更多信息:https://mongoosejs.com/docs/api/schema.html#schema_Schema.Types

暫無
暫無

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

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