[英]Referencing another schema in Mongoose
如果我有两个模式,如:
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}],
});
我试图像上面的例子一样将它们连接在一起,但我不知道该怎么做。 最终,如果我能做这样的事情,我的生活就会变得很轻松
var profilePic = Post.postedBy.profilePic
听起来 populate 方法正是您要找的。 首先对您的帖子架构进行小的更改:
var postSchema = new Schema({
name: String,
postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
然后制作你的模型:
var Post = mongoose.model('Post', postSchema);
然后,当您进行查询时,您可以像这样填充引用:
Post.findOne({_id: 123})
.populate('postedBy')
.exec(function(err, post) {
// do stuff with post
});
附录:没有人提到“填充”——看猫鼬填充方法非常值得你花时间和金钱:还解释了交叉文档引用
回复晚了,但补充说Mongoose也有子文档的概念
使用此语法,您应该能够将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}],
});
请注意类型为userSchema
的更新后的postedBy
字段。
这会将用户对象嵌入帖子中,从而节省了使用引用所需的额外查找。 有时这可能更可取,其他时候 ref/populate 路线可能是要走的路。 取决于您的应用程序在做什么。
{body: "string", by: mongoose.Schema.Types.ObjectId}
mongoose.Schema.Types.ObjectId
将创建一个新的 id,尝试将其更改为更直接的类型,例如 String 或 Number。
这是对 D. Lowe 的回答的补充,它对我有用但需要一些调整。 (我会将此作为评论,但我没有这样做的声誉,我希望在几个月后再次遇到此问题时看到此信息,但我忘记了如何解决它。)
如果您从另一个文件导入架构,则需要将 .schema 添加到导入的末尾。
注意:如果您没有导入架构而是使用本地架构,我不确定您是否获得了无效的架构配置,但导入对我来说更清晰、更容易处理。
例如:
// ./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);
然后,无论您在哪里使用它(对我来说,我在 Node.js API 中使用了与此类似的代码),您都可以简单地将 other 分配给 master。
例如:
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.