我正在开展一个项目,我需要在Mongo数据库中比较一个集合与另一个集合的数据。具体而言,用户偏好和车辆数据。我希望将用户选择的车辆与库存中的匹配车辆匹配。
问题:如何使用我从用户选择(javascript对象)获得的最小年份和最长年份,并创建一个与车辆年份匹配的查询?
到目前为止,我已经采用了每个用户并将选择数组(选择)映射到类别数组(minYear,maxYear,make,model),并使用$ in运算符成功匹配make和model。现在,我很困惑如何用一两个可能的年份来做同样的事情。我尝试使用$ gte和$ in,但是......没有运气。
这是我的代码:
const inv = db.collection('inventory'), users = db.collection('users')
users.find().toArray((err, docs) => {
if (err) throw new Error(err)
const users = docs
for (var i = 0; i < users.length; i++) {
let user = users[i],
userId = user._id,
picks = user.profile.picks,
minYears = picks.map(pick => {
return pick.minYear
}),
maxYears = picks.map(pick => {
return pick.maxYear
}),
makes = picks.map(pick => {
return pick.make.toUpperCase()
}),
models = picks.map(pick => {
return pick.model.toUpperCase()
}),
yards = user.profile.yards.map(yard => {
return yard.yard
})
console.log(minYears)
inv
.find({
year: { $gte: { $in: minYears }, $lte: { $in: maxYears } },
make: { $in: makes },
model: { $in: models },
yardName: { $in: yards }
})
.toArray((err, docs) => {
if (err) throw new Error(err)
console.log(
`Customer with mobile number ${user.profile.mobile} has ${docs.length} matches.`)
})
}
这就是我的用户数组的样子:
[
user1: {
id,
profile: {
picks: [
{ minYear, maxYear, make, model },
{ minYear, maxYear, make, model },
{ minYear, maxYear, make, model }
],
yards: [
{ yardName1, yardName2, yardName3 }
]
}
},
user2: {
id,
profile: {
picks: [
{ minYear, maxYear, make, model },
{ minYear, maxYear, make, model }
],
yards: [
{ yardName1, yardName2 }
]
}
}
]
感谢您提供任何帮助!