簡體   English   中英

如何將貓鼬模型引用到另一個模型?

[英]How do I reference mongoose model to another model?

我有一個類似這樣的故事的貓鼬模式:

{
    id: {
        type: Number,
        default: 0
    },
    title: {
        type: String,
        maxLength: 60
    },
    author: {
        userid: {
            type: Number
        },
        username: {
            type: String
        }
    }
    chapters: [chapter],
    numchapters: {
        type: Number,
        default: 1
    },
    favs: {
        type: Number,
        default: 0
    },
    completed: {
        type: Boolean,
        default: false
    }
}

我想要做的是在單獨的集合 ( users ) 中引用文檔,並在author字段中使用其useridusername字段的值。 我該怎么做呢?

當前代碼:

storyobj.populate('author', {path: 'author', model: 'users', select: 'userid username'}, (err) => {
            if (err) {
                console.log(err)
            }
        })

以防萬一, users集合的結構如下所示:

{
    username: {
        type: String,
    },
    email: {
        type: String,
    },
    password: {
        type: String,
    },
    userid: {
        type: Number
    },
    isAdmin: {
        type: Boolean,
        default: false
    },
    banned: {
        type: Boolean,
        default: false
    }
}

編輯:

我已將 Stories 模型中的author字段更改為如下所示:

    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    }

所以我告訴 Mongoose,“嘿,我希望這個字段引用用戶集合中的用戶”。

這里有一些更多的細節,我希望會有所幫助。

完整代碼:

var storydb = require('../models/stories/story');
var chapterdb = require('../models/stories/chapter');
var userdb = require('../models/user');

const file = JSON.parse(fs.readFileSync('test.json')); // this is a file with the data for the stories I am trying to insert into my database

for (const d in file) {
    var storyobj = new storydb({
        id: d,
        chapters: []
    });
    for (let e = 0; e < file[d].length; e++) {
        var abc = file[d][e];
        var updatey = {
            chaptertitle: abc.chapter,
            chapterid: parseInt(abc.recid),
            words: abc.wordcount,
            notes: abc.notes,
            genre: abc.gid.split(', '),
            summary: abc.summary,
            hidden: undefined,
            loggedinOnly: undefined,
            posted: new Date(Date.parse(abc.date)),
            bands: abc.bandnames.split(', ')
        };
        var kbv = getKeyByValue(userlookup, abc.uid);
        
        storyobj.title = abc.title;
        storyobj.numchapters = file[d].length;
        storyobj.favs = file[d][0].numfavs;
        updatey.characters = abc.charid.split(/, |,/g);
        
        storyobj.chapters.push(updatey)
    }
    storyobj.save();
}

file ,有一個唯一 ID代表每個故事的作者。 kbv返回與該唯一 ID 關聯的用戶 ID(請注意,它們不相同)。

現在,這就是我遇到麻煩的地方:

我想要做的是在kbv找到與 userid 匹配的用戶, kbv故事模型中的author屬性。

我目前用來嘗試實現這一目標的代碼:

storydb.findOne({storyobj}, 'author').populate("author", (f) => console.log(f));
const Stories = require("./path/to/model");

Stories
    .find({ /* query */ }, { /* projection */ })
    .populate("author.username", ["userid", "username"])
    .then(/* handle resolve */)
    .catch(/* handle rejection */)

為此,您必須向模型中的userid鍵添加一個ref鍵,其中ref值是它所引用的模型的名稱。

Story.model.js

const StorySchema = new Schema({
    author: {
        userid: { type: Schema.Types.ObjectId, ref: "users", required: true },
        /* other props */
    }
    /* other props */
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM