Mongoose,查找包含对象数组中值的文档

时间:2016-04-10 05:40:03

标签: javascript node.js mongodb mongoose

我有一个Project架构,其中有一个名为collaborators的字段。 collaborators字段是User个对象的数组。 User对象包含一个名为username的字段。我想找到collaborator的所有项目都与requestor's用户名具有相同的用户名。这是我提出的查询,但它什么也没有返回。

Project.find({ 'collaborators.username': req.user.username })

如果我能提供任何其他有用的信息,请告诉我。

项目架构

var ProjectSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    creator: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    description: {
        type: String,
        default: ''
    },
    name: {
        type: String,
        default: '',
        required: 'Please fill Project name',
        trim: true
    },
    phase: {
        type: Number,
        default: ''
    },
    sponsor: {
        type: String,
        default: '',
        trim: true
    },
    collaborators: [{
        type: Schema.ObjectId,
        ref: 'User'
    }],
    emailInvitees: {
        type: Array,
        default: []
    },
    userInvitees: {
        type: Array,
        default: []
    },
    comments: {
        type: String,
        default: ''
    }
});

用户架构

var UserSchema = new Schema({
    firstName: {
        type: String,
        trim: true,
        default: '',
        validate: [validateLocalStrategyProperty, 'Please fill in your first name']
    },
    lastName: {
        type: String,
        trim: true,
        default: '',
        validate: [validateLocalStrategyProperty, 'Please fill in your last name']
    },
    organization: {
        type: String,
        trim: true,
        default: '',
        required: 'Please fill in an organization name'
    },
    position: {
        type: String,
        trim: true,
        default: '',
        required: 'Please fill in the title of your position'
    },
    displayName: {
        type: String,
        trim: true
    },
    email: {
        type: String,
        trim: true,
        default: '',
        validate: [validateLocalStrategyProperty, 'Please fill in your email'],
        match: [/.+\@.+\..+/, 'Please fill a valid email address']
    },
    username: {
        type: String,
        unique: 'testing error message',
        required: 'Please fill in a username',
        trim: true
    },
    password: {
        type: String,
        default: '',
        validate: [validateLocalStrategyPassword, 'Password should be longer']
    },
    salt: {
        type: String
    },
    provider: {
        type: String,
        required: 'Provider is required'
    },
    providerData: {},
    additionalProvidersData: {},
    roles: {
        type: [{
            type: String,
            enum: ['user', 'admin']
        }],
        default: ['user']
    },
    updated: {
        type: Date
    },
    created: {
        type: Date,
        default: Date.now
    },
    /* For reset password */
    resetPasswordToken: {
        type: String
    },
    resetPasswordExpires: {
        type: Date
    }
});

0 个答案:

没有答案