【问题标题】:Reference another Schema in Mongoose在 Mongoose 中引用另一个 Schema
【发布时间】:2021-07-31 15:02:47
【问题描述】:

所以我必须使用 Schemas。 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 中引用用户对象 ID。如您所见,我使用 type: mongoose.Schema.Types.ObjectID 完成了该操作。我已经多次看到这一点。但在我的数据库中,用户从未出现在文档中。我需要做什么?

干杯

【问题讨论】:

  • 那么,您想在您的帖子文档中嵌入用户还是在您的用户文档中嵌入帖子?
  • 我想在我的帖子文档中嵌入用户

标签: javascript node.js mongodb mongoose mongoose-schema


【解决方案1】:

引用文档和嵌入文档是有区别的。

如果您想将文档存储在文档中,您应该将其嵌入,这样读取操作会更快,因为您不需要执行 JOIN 操作。

虽然引用意味着存储您正在引用的实体的 ID,但当您需要访问您正在引用的文档时,您需要通过您存储的 ID 从集合中获取它。它比嵌入慢,但它为您提供更高的一致性和数据完整性,因为数据在集合中存储一次,而不是在每个对象中重复。而且 MongoDB 不支持外键,所以你应该小心引用。

因此,当您使用ref 存储文档时,您需要将ObjectID 作为user,然后获取您需要添加populate 调用的文档。例如

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

【讨论】:

    【解决方案2】:

    尝试保存在变量中:

    const UserId = UserSchema.Schema.Types.ObjectId;

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

    【讨论】:

      猜你喜欢
      • 2020-09-26
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 2021-02-25
      • 2021-03-27
      • 2021-04-09
      • 2018-06-07
      相关资源
      最近更新 更多