[英]Referencing another schema in Mongoose
if I have two schemas like:如果我有两个模式,如:
var userSchema = new Schema({
twittername: String,
twitterID: Number,
displayName: String,
profilePic: String,
});
var User = mongoose.model('User')
var postSchema = new Schema({
name: String,
postedBy: User, //User Model Type
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
I tried to connect them together like the example above but I couldn't figure out how to do it.我试图像上面的例子一样将它们连接在一起,但我不知道该怎么做。 Eventually, if I can do something like this it would make my life very easy
最终,如果我能做这样的事情,我的生活就会变得很轻松
var profilePic = Post.postedBy.profilePic
It sounds like the populate method is what your looking for.听起来 populate 方法正是您要找的。 First make small change to your post schema:
首先对您的帖子架构进行小的更改:
var postSchema = new Schema({
name: String,
postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
Then make your model:然后制作你的模型:
var Post = mongoose.model('Post', postSchema);
Then, when you make your query, you can populate references like this:然后,当您进行查询时,您可以像这样填充引用:
Post.findOne({_id: 123})
.populate('postedBy')
.exec(function(err, post) {
// do stuff with post
});
Addendum: No one mentioned "Populate" --- it is very much worth your time and money looking at Mongooses Populate Method : Also explains cross documents referencing附录:没有人提到“填充”——看猫鼬填充方法非常值得你花时间和金钱:还解释了交叉文档引用
http://mongoosejs.com/docs/populate.html http://mongoosejs.com/docs/populate.html
Late reply, but adding that Mongoose also has the concept of Subdocuments回复晚了,但补充说Mongoose也有子文档的概念
With this syntax, you should be able to reference your userSchema
as a type in your postSchema
like so:使用此语法,您应该能够将
userSchema
引用为userSchema
中的类型, postSchema
所示:
var userSchema = new Schema({
twittername: String,
twitterID: Number,
displayName: String,
profilePic: String,
});
var postSchema = new Schema({
name: String,
postedBy: userSchema,
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
Note the updated postedBy
field with type userSchema
.请注意类型为
userSchema
的更新后的postedBy
字段。
This will embed the user object within the post, saving an extra lookup required by using a reference.这会将用户对象嵌入帖子中,从而节省了使用引用所需的额外查找。 Sometimes this could be preferable, other times the ref/populate route might be the way to go.
有时这可能更可取,其他时候 ref/populate 路线可能是要走的路。 Depends on what your application is doing.
取决于您的应用程序在做什么。
{body: "string", by: mongoose.Schema.Types.ObjectId}
mongoose.Schema.Types.ObjectId
将创建一个新的 id,尝试将其更改为更直接的类型,例如 String 或 Number。
This is in addition to D. Lowe's answer which worked for me but needed a bit of tweaking.这是对 D. Lowe 的回答的补充,它对我有用但需要一些调整。 (I would have put this as a comment but I don't have the reputation to do so, and I would like to see this information in a few months when I encounter this issue again but I forget how to solve it.)
(我会将此作为评论,但我没有这样做的声誉,我希望在几个月后再次遇到此问题时看到此信息,但我忘记了如何解决它。)
If you are importing a Schema from another file, then you will need to add .schema to the end of the import.如果您从另一个文件导入架构,则需要将 .schema 添加到导入的末尾。
Note: I am unsure if you get the Invalid schema configuration if you are not importing schemas and using local schemas instead but importing is just cleaner and easier to handle for me.注意:如果您没有导入架构而是使用本地架构,我不确定您是否获得了无效的架构配置,但导入对我来说更清晰、更容易处理。
For example:例如:
// ./models/other.js
const mongoose = require('mongoose')
const otherSchema = new mongoose.Schema({
content:String,
})
module.exports = mongoose.model('Other', otherSchema)
//*******************SEPERATE FILES*************************//
// ./models/master.js
const mongoose = require('mongoose')
//You will get the error "Invalid schema configuration: `model` is not a valid type" if you omit .schema at the end of the import
const Other=require('./other').schema
const masterSchema = new mongoose.Schema({
others:[Other],
singleOther:Other,
otherInObjectArray:[{
count:Number,
other:Other,
}],
})
module.exports = mongoose.model('Master', masterSchema);
Then, wherever you use this (for me I used code similar to this in my Node.js API) you can simply assign other to master.然后,无论您在哪里使用它(对我来说,我在 Node.js API 中使用了与此类似的代码),您都可以简单地将 other 分配给 master。
For example:例如:
const Master= require('../models/master')
const Other=require('../models/other')
router.get('/generate-new-master', async (req, res)=>{
//load all others
const others=await Other.find()
//generate a new master from your others
const master=new Master({
others,
singleOther:others[0],
otherInObjectArray:[
{
count:1,
other:others[1],
},
{
count:5,
other:others[5],
},
],
})
await master.save()
res.json(master)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.