引用Mongoose中的另一个模式

Referencing another schema in Mongoose

本文关键字:另一个 模式 Mongoose 引用      更新时间:2023-09-26

如果我有两个模式,比如:

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
});

附录:没有人提到"Populate"——看看Mongooses Populate方法非常值得你花时间和金钱:还解释了引用的交叉文档

http://mongoosejs.com/docs/populate.html

回复较晚,但补充说Mongoose也有Subdocuments 的概念

使用此语法,您应该能够将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字段。

这将在帖子中嵌入用户对象,从而节省使用引用所需的额外查找。有时这可能更可取,其他时候引用/填充路线可能是可取的。这取决于你的应用程序在做什么。

这是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中使用了类似的代码),你都可以简单地将其他分配给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)
})
{body: "string", by: mongoose.Schema.Types.ObjectId}

mongoose.Schema.Types.ObjectId将创建一个新的id,尝试将其更改为更直接的类型,如String或Number。