Node.js NodeJS Mongoose关系外键
好的,我正在尝试猫鼬来创建一些模型 我的用户模型是这样的,我的帖子模型看起来几乎相同,但字段不同。问题是,如何在这两个模型之间建立关系?一个用户可能有许多帖子,而一篇帖子可能属于一个用户。 这是我非常不理解的,因为MySQL中没有外键Node.js NodeJS Mongoose关系外键,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,好的,我正在尝试猫鼬来创建一些模型 我的用户模型是这样的,我的帖子模型看起来几乎相同,但字段不同。问题是,如何在这两个模型之间建立关系?一个用户可能有许多帖子,而一篇帖子可能属于一个用户。 这是我非常不理解的,因为MySQL中没有外键 /*----------------------------------------------------------------. | Require modules
/*----------------------------------------------------------------.
| Require modules |
'-----------------------------------------------------------------*/
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
/*----------------------------------------------------------------.
| A model needs a scheme that starts with a |
| constant that are named to define the scheme |
'-----------------------------------------------------------------*/
let userSchema = new Schema({
username: {
type: String,
required: true,
min: 4, max: 16,
unique: true
},
password: {
type: String,
min: 4,
required: true
},
email: {
type: String,
unique: true,
required: true
},
lastSeen: Date,
});
/*----------------------------------------------------------------.
| Add timestamps |
| created_at |
| updated_at |
'-----------------------------------------------------------------*/
userSchema.set('timestamps', true);
/*----------------------------------------------------------------.
| Plugins! |
'-----------------------------------------------------------------*/
userSchema.plugin(require('mongoose-paginate'));
/*----------------------------------------------------------------.
| Define the model |
'-----------------------------------------------------------------*/
let User = mongoose.model('User', userSchema);
module.exports = User;
将以下内容放入用户模式中是否正确
posts: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}]
或者这是错误的 没错!此外,为了在获取用户时填充posts字段,您需要添加以下内容:
this.find(query).populate('posts').exec();
希望有帮助 我建议为每篇文章创建一个用户id字段,当你的规模扩大时,事情会很快失控。