[英]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
命令的信息,但它似乎用于包含子数组的文档,而不是特定的子文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.