简体   繁体   中英

Reference another Schema in Mongoose

so I have to Schemas. PostSchema and 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)

UserSchema:

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

My question is: I'm trying to reference the User Object ID in the Post Schema. As you can see, I've done that with type: mongoose.Schema.Types.ObjectID. And I've seen this multiple times. But in my database, the User never shows up in the Document. What do I need to do?

Cheers

There is a difference between referencing a document and embedding a document.

If you want to store a document inside a document you should embed it, thus read operations will be faster because you won't need to perform JOIN operations.

Whereas referencing means storing an ID of an entity that you are referencing, when you need to access the document you are referencing, you need to fetch it from the collection by the ID you have stored. It is slower than embedding, but it gives you higher consistency and data integrity because the data is stored once at the collection and not duplicated at every object. And MongoDB does not support foreign keys so you should be careful with referencing.

So when you are storing the document using ref , you need to put an ObjectID as a user and then fetch the document you need to add populate call. eg

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

try to save in a variable:

 const UserId = UserSchema.Schema.Types.ObjectId;

for more information:https://mongoosejs.com/docs/api/schema.html#schema_Schema.Types

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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