我正在尝试在一个集合中查找find()并将该值连接到随后的find()返回的正确对象。但是我不能保证在第一个find()中检索到的值将与index匹配。如何确保将第一个值(布尔值)附加到第二个find()的正确实例上?
到目前为止,我所使用的是第一个条件的索引,但是如果实例被删除,它可能不匹配
我的模特:
let Instance= new Schema({
imgName: String,
offer: String,
brand: String,
desc: String,
keywords: Array,
loc: String,
location: {
type: {
type: String, // Don't do `{ location: { type: String } }`
enum: ['Point'], // 'location.type' must be 'Point'
required: true
},
coordinates: {
type: [Number],
required: true
}
},
categories: Array,
userId: String,
active: Boolean,
stockPic: String,
startTime: Number,
endTime: Number,
range: Boolean
});
mongoose.model('Beams2', Instance);
let LikesSchema = new Schema({
userId: String,
likeId: String,
categories: Array,
public: Boolean
});
mongoose.model('Likes', LikesSchema);
//My query:
exports.findAllLikes = function(req, res){
Likes.find({'userId': req.body.userId}, function(err, results) {
let likeIds = results.map((currentValue, index, array) => {
return currentValue.likeId;
});
let statusArr = results.map((currentValue, index, array) => {
return currentValue.public;
});
Instances.find({'_id': { $in: likeIds }}, function(err, favs){
if (err) return console.log(err);
let newArr = [];
favs.forEach(function(element, i) {
//console.log(statusArr[i]);
let post = element.toObject();
post.public = statusArr[i]; //need to guarantee correct value
newArr.push(post);
console.log(post);
});
return res.send(newArr);
});
});
};
答案 0 :(得分:0)
我认为,这是您可以实现想要的目标的方法:
exports.findAllLikes = function(req, res) {
Likes.find({
'userId': req.body.userId
}, (err, results) => {
if (err) {
console.log('Error while fetching likes: ', err);
return res.status(500).json({
Error: 'Error while fetching likes.'
});
}
const likeIds = results.map(({
likeId
}) => likeId);
Instances.find({
'_id': {
$in: likeIds
}
}, (err, favs) => {
if (err) {
console.log('Error while fetching likes: ', err);
return res.status(500).json({
Error: 'Error while fetching Instances.'
});
}
let newArr = [];
favs.forEach((elem) => {
let post = elem.toObject();
const likeDoc = results.find(({
likeId
}) => likeId === post._id.toString());
post.public = (likeDoc && likeDoc.public) ? likeDoc.public : '';
newArr.push(post);
});
console.log(post);
return res.status(200).send(newArr);
});
});
};
除非您确定自己具有相同的长度数组,否则不要使用索引来映射内容。
希望这会有所帮助:)