NodeJS猫鼬关系外键

时间:2019-06-13 20:26:44

标签: node.js mongodb mongoose

好的,所以我正在尝试猫鼬来创建一些模型。

我的用户模型看起来像这样,而我的帖子模型看起来几乎相同,但是具有不同的字段。问题是,如何在这两个模型之间建立关系?一个用户可能有很多帖子,而一个帖子可能属于一个用户。 那是我完全不了解的,因为没有像MySQL这样的外键。

/*----------------------------------------------------------------.
|    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'
}]

这是错误的吗?

1 个答案:

答案 0 :(得分:1)

是的!另外,为了在吸引用户时填充帖子字段,您需要添加以下内容:

this.find(query).populate('posts').exec();

希望有帮助!