如何使用其他集合的子数组数据过滤mongo集合子数组中的数据

时间:2019-08-13 09:02:00

标签: javascript node.js mongodb mongoose

大规模地制作一个node.js,mongodb具有添加好友功能,其中列表用户可以选择在好友列表中添加,发送好友请求,接受好友请求,删除好友请求,阻止好友请求。

注册收藏

const mongoose = require('mongoose');

const Schema = mongoose.Schema;


let Register = new Schema(
    First_Name:{
        type: String,
        required: true   
    },
    Last_Name: {
        type: String
    },
    Email: {
        type: String,
        unique: true,
        lowercase: true,
        required: true
    },
    Friends:[{type: String}],  
});

module.exports = mongoose.model('Register', Register);

朋友收藏

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var ObjectId = require('mongodb').ObjectID;
let Friends = new Schema({
    Requester: {
        type: ObjectId,
        required: true
    },
    Recipients: [{Recipient:{type:ObjectId},Status:{type:Number}}],


}); 
module.exports = mongoose.model('Friends', Friends);

内部Node.js Post API

var Register = require('../models/register.model');
var Friends =require('../models/friends.model');

router.post('/getdata',function(req,res)
{
let Email="example@example.com";

Register.findOne({ Email : Emails }, function(err, user) {

Friends.findOne({ Requester :user._id  }, function(err, user1) {

Register.find({$and:[{Friends:{$nin:[user._id]}},{_id:{$ne:user1.Recipients.Recipient}}]},function(err, user2) {

console.log("user2",user2);

//Here User2 data is not coming

//How to get data so can able to list user that is not added yet in FriendList

//Mainly user1.Recipients.Recipient this is not working because //Recipients is array so how can match all data with array, if i am //using loop then find return data scope ends on inside find closing //braces only.


//Any suggestion

 });

 });
});

2 个答案:

答案 0 :(得分:1)

因此,如果我正确,则需要执行以下操作:

  1. 根据给定的电子邮件查找注册
  2. 找到与此用户相关的朋友
  3. 查找尚未在用户的好友列表中的注册

同样,考虑到您键入的内容,我假设A可以是B的朋友,但这并不意味着B是A的朋友。

虽然您当前拥有的数据结构可能并非最佳选择,但我将向您显示适当的查询:

var Register = require('../models/register.model');
var Friends =require('../models/friends.model');

router.post('/getdata',function(req,res) {
    const email = "example@example.com";

    Register.findOne({ Email: email }, function(err, user) { 
        if (err) {
             console.error(err);
             return;
        }

        Friends.findOne({ Requester: user._id }, function(err, friend) {
            if (err) {
                console.error(err);
                return;
            }

            const reciptientIds = friend.Recipients.map(function (recipient) {
                return recipient.Recipient.toString();
            });

            Register.find({Friends: { $ne: user._id }, {_id: { $nin: recipientIds }}, function(err, notFriendedUsers) {
                if (err) {
                    console.error(err);
                    return;
                }

                console.log(notFriendedUsers);
            });
        });
    });
});

P.S。可以使用promise或await / defer轻松减少这种“回调地狱”

答案 1 :(得分:0)

终于可以解决了,下面是解决方法

var Register = require('../models/register.model');
var Friends =require('../models/friends.model');

router.post('/getdata',function(req,res)
{
let Emails="example@example.com";

 Register.findOne({$and:[{ Email : Emails}] }, function(err, user) { 
              if (err) {
                   console.error(err);
                   return;
              }

              Friends
              .findOne({ Requester: user._id }, 
                    { _id: 0} )
              .sort({ Recipients: 1 })
              .select( 'Recipients' )
              .exec(function(err, docs){
                  docs = docs.Recipients.map(function(doc) { 
                    return doc.Recipient; });
                  if(err){
                      res.json(err)
                  } else {
                    console.log(docs,"docs");
                      Register.find({$and:[{Friends: { $ne: user._id }},{_id: { $nin: docs }},{_id:{$ne:user._id}}]}, function(err, notFriendedUsers) {
                        if (err) {
                            console.error(err);
                            return;
                        }

                        console.log(notFriendedUsers);
                    });

                  }
              })
            });