【发布时间】:2020-05-26 07:04:30
【问题描述】:
我在 Mongoose 中有这个架构
ProfileEmailSchema = module.exports = mongoose.Schema({
username: {
type: String,
unique: true,
index: true,
required: true
},
password: {
type: String,
required: true
},
profile: { type: Number, unique: true, required: true, index: true },
email: {
type: String,
required: true,
unique: true,
index: true
},
fullname: {
type: String,
required: true
},
display_picture: {
type: String
},
isProfileCompleted: {
type: Boolean,
deafult: false
},
profile: created_at: { type: Date, default: Date.now },
updated_at: { type: Date, default: Date.now }
});
ProfileEmailSchema.pre('save', function(next) {
log("Saving Profile Data :");
now = new Date();
this.updated_at = now;
if (!this.created_at) {
this.created_at = now
}
next();
});
ProfileEmailSchema.pre("save", function(next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
});
// test Function
ProfileEmailSchema.methods.find = function(cb) {
this.model('ProfileEmailModel').findOne({}, cb);
};
//Pass Comparison Function
ProfileEmailSchema.methods.comparePassword = function(password, cb) {
log("Compare Password with HASHED pass");
log(password);
log("HASHED");
log(this.password);
bcrypt.compare(password, this.password, function(err, isMatch) {
if (err) return cb(err);
log("Return Status:");
log(isMatch);
cb(null, isMatch);
});
};
ProfileEmailModel = module.exports = mongoose.model("ProfileEmailModel", ProfileEmailSchema);
我面临的问题是我需要在执行以下操作时将 _id 复制到配置文件字段
var tuple = new UserProfileModel({
username: profile.username,
email: profile.email,
fullname: profile.fullname,
password: profile.password,
});
console.log(tuple);
我正在尝试这样使用但无济于事
var tuple = new UserProfileModel({
username: profile.username,
email: profile.email,
fullname: profile.fullname,
password: profile.password,
profile : mongoose.Schema.Types.ObjectId
});
console.log(tuple);
但它不工作。在使用tuple.save() 创建第一个文档时,我需要确保在创建新文档时将_id 复制到profile 键。
请建议。否则我将需要在应用程序中进行更改,这将是 4 个月。
【问题讨论】:
-
所以,如果
_id是由 MongoDB 在插入时创建的,您不能将它们复制到profile,而是可以在您的客户端创建_id并将其复制到profile然后保存..
标签: javascript mongodb mongoose mongodb-query mongoose-schema