我有两个mongoose模式'user'和'project',我想在mysql中显示这些模式之间的关系。这该怎么做? 如何在创建项目时传递用户?
user.js的
const mongoose = require('mongoose');
const bcrypt = require('bcrypt-nodejs');
const Schema = mongoose.Schema();
const UserSchema = mongoose.Schema({
fullname: {type: String},
username : {type:String},
password: {type:String}
});
UserSchema.methods.encryptPassword = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(10), null);
};
UserSchema.methods.comparePassword = function(userPassword, cb) {
bcrypt.compare(userPassword, this.password, (err, isMatch) => {
if(err) throw err;
cb(null, isMatch);
});
}
module.exports = mongoose.model('User', UserSchema);
project.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema();
const User = require('./user');
const ProjectSchema = mongoose.Schema({
title: {type: String, required: true},
description: {type:String},
created_at: { type: Date, default: Date.now },
publish : { type: Boolean, default: false}
});
module.exports = mongoose.model('Project', ProjectSchema);
答案 0 :(得分:1)
在Mongoose中创建模式与在Relational DBMS中创建模式不同,例如MySQL,PostGreSQL。
您可以使用objectId,bro。
如果一个项目只能由一个用户处理,你可以使用这样的东西。
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
但是如果一个项目由多个用户处理
users: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
希望它会有所帮助