Mongoose:查找所有引用的文档

时间:2016-12-29 06:43:03

标签: node.js mongodb mongoose mongoose-schema

我有2个架构:

var pollSchema = new mongoose.Schema({
    title: String,      
    created: {
        type: Date, default: Date.now
    },
    options: [{
        label: String,
        count: {
            type: Number,  default: 0
        },
        backgroundColor: {
            type: String,  default: '#fff'
        }
    }],
    author:{
        id:{
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },              
        username: String        
    }
});



var userSchema = new Schema({
    username: {type: String, unique:true},
    email: {type: String, unique:true, lowercase: true},
    password: String
});

现在每个民意调查都会存储其作者的数据。 问题:

  • 如何重新设计我的架构 - 所以我将能够找到属于特定用户的所有民意调查?
  • 或者我应该保留相同的模式并找到另一种方法吗?

1 个答案:

答案 0 :(得分:1)

您仍然可以找到属于特定用户的所有民意调查。你有author.id。

此外,您可以将数组保留为var userSchema = new Schema({ username: {type: String, unique:true}, email: {type: String, unique:true, lowercase: true}, password: String, polls: [] });

每次用户轮询时,都会在polls数组中推送userId,以后可以填充或获取计数。