繁体   English   中英

如何通过子属性在mongoose中查找文档?

[英]How to find a document in mongoose by child property?

我的项目中有这个Person和User模型:

const mongoose = require('mongoose');
const Schema = mongoose.Schema; 

const schema = new Schema({

    name: {
        type: String,
        required: true
    }
});

module.exports = mongoose.model('Person', schema);

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const schema = new Schema({

    person: {
        type: mongoose.SchemaTypes.ObjectId,
        ref: 'Person',
        required: true
    },

    email: {
        type: String,
        required: true
    }
});

module.exports = mongoose.model('User', schema);

我们可以看到,用户可以引用Person。 我试图通过他的电子邮件或他的人的名字找到一个用户。 我尝试了很多不同的方法,比如:

exports.getUserByPersonNameOrEmail = async (uservalue) => {
    var user = await User.findOne({
        $or: [
            {"person.name": uservalue},
            {email: uservalue}
        ]
    });
    return user;
};

我还阅读了有关使用$elemMatch命令的信息,但它似乎用于包含子数组的文档,而不是特定的子文件。

你必须在populate期间使用mongoose populate及其match步骤:

var user = await User.findOne({}).populate({
  path: 'person',
  match: { name: uservalue }, 
  select: 'name -_id'
}).exec()

你可以在这里阅读更多相关信息 这个想法基本上是你必须在你的使用模型中populateperson的实际引用,以便查询它们。 match在填充过程match应用过滤器等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM