[英]How do I reference mongoose model to another model?
I have a mongoose schema for stories that looks like this:我有一个类似这样的故事的猫鼬模式:
{
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
}
}
What I'm trying to do is reference a document in a separate collection ( users
), and use the values of its userid
and username
fields in the author
field.我想要做的是在单独的集合 (
users
) 中引用文档,并在author
字段中使用其userid
和username
字段的值。 how do I do this?我该怎么做呢?
current code:当前代码:
storyobj.populate('author', {path: 'author', model: 'users', select: 'userid username'}, (err) => {
if (err) {
console.log(err)
}
})
just in case it's relevant, the structure of the users
collection looks like this:以防万一,
users
集合的结构如下所示:
{
username: {
type: String,
},
email: {
type: String,
},
password: {
type: String,
},
userid: {
type: Number
},
isAdmin: {
type: Boolean,
default: false
},
banned: {
type: Boolean,
default: false
}
}
EDIT:编辑:
I've changed the author
field in the Stories model to look like this:我已将 Stories 模型中的
author
字段更改为如下所示:
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
This is so I tell Mongoose, "Hey, I want this field to reference a user in the User collection".所以我告诉 Mongoose,“嘿,我希望这个字段引用用户集合中的用户”。
Here are some more details that I hope will be of help.这里有一些更多的细节,我希望会有所帮助。
Full code:完整代码:
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();
}
In file
, there's a unique ID representing the author of each story.在
file
,有一个唯一 ID代表每个故事的作者。 kbv
returns the userid associated with that unique ID ( note that they're NOT the same ). kbv
返回与该唯一 ID 关联的用户 ID(请注意,它们不相同)。
Now, here's where I'm having trouble:现在,这就是我遇到麻烦的地方:
What I want to do is find a user matching the userid in kbv
, and make that the author
property in the story model.我想要做的是在
kbv
找到与 userid 匹配的用户, kbv
故事模型中的author
属性。
The code I'm currently using to try and achieve that:我目前用来尝试实现这一目标的代码:
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 */)
For this to work, you have to add a ref
key to the userid
key in your model, where the ref
value is the name of the model it's referencing.为此,您必须向模型中的
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.