首页 > 解决方案 > 如何使用 mongoose refs 存储参考数据?

问题描述

我正在制作一个笔记应用程序,每个笔记都有多个类别。

var NotesSchema = new mongoose.Schema({
    title: String,
    note: String, 
    favorite: {type: Boolean, default: false},
    category: [{ type: mongoose.Schema.Types.ObjectId, ref: "categories" }]
},{ timestamps: { createdAt: 'created_at' } });

var Notes = mongoose.model('Notes', NotesSchema);

var CategoriesSchema = new Schema({
    name: {type: String, required: true},
    favorite: {type: Boolean, default: false}, 
})
var Categories = mongoose.model('Categories', CategoriesSchema);

我只能对一个类别执行此操作,但我不知道如何对多个类别执行此操作。

首先,我认为我需要存储类别,获取每个 ID,然后存储注释。这是我尝试过的:

.get('/', (req, res) => {
    var data = {
        title : "scientific revolution",      
        note : " some note", 
        favorite : true,    
        category : [ 'science', 'books']
    }
    var catIds = [], seriesIds = [];

    data.category.map(cat =>{
        const category = new Categories({
            name: cat
        })
        category.save((err,data)=>{
            if(err) throw err; 
            catIds.push(data._id)
        })
    })
    data.category = catIds; 
    const note = new Notes(data)
    note.save((err, data)=>{
        if(err) throw err;
        res.json(data)
    })
})

数组catIds永远不会得到 id!

我对使用参考完全陌生。甚至不知道它们的存在。

标签: node.jsmongodbmongoose

解决方案


Your ref field should point to the model name not the table name.

In this case Categories.

I see you have write {ref: 'categories'} with small c but mongoose collection name is case sensitive and you should do {ref: 'Categories'}.

You can read more about mongoose case sensitivity in this post


推荐阅读