所以我必须使用模式。 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 完成了这项工作。我已经多次看到这种情况。但是在我的数据库中,用户永远不会出现在文档中。我需要做什么?
干杯
答案 0 :(得分:0)
引用文档和嵌入文档是有区别的。
如果你想在一个文档中存储一个文档,你应该嵌入它,这样读取操作会更快,因为你不需要执行 JOIN 操作。
引用意味着存储您正在引用的实体的 ID,当您需要访问您正在引用的文档时,您需要通过您存储的 ID 从集合中获取它。它比嵌入慢,但它为您提供更高的一致性和数据完整性,因为数据在集合中存储一次,而不是在每个对象中重复。而且 MongoDB 不支持外键,所以在引用时要小心。
因此,当您使用 ref
存储文档时,您需要将 ObjectID
作为 user
,然后获取需要添加 populate
调用的文档。例如
PostShema.findOne({ _id: SomeId }).populate('user');
答案 1 :(得分:0)
尝试保存在变量中:
const UserId = UserSchema.Schema.Types.ObjectId;
了解更多信息: https://mongoosejs.com/docs/api/schema.html#schema_Schema.Types