繁体   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