【问题标题】:find user details from array of object ids从对象 ID 数组中查找用户详细信息
【发布时间】:2020-01-09 21:09:41
【问题描述】:

我有一个从另一个实例中提取的对象 ID 数组。 这些对象 ID 代表用户模型中的用户 ID。我想使用这些对象 id 来获取用户详细信息

我是如何获得对象 ID 的

        const chatrooms = await ChatRoom.find({owners:{$all:[user._id]}}) 
        const allowners = chatrooms.flatMap(room => room.owners) 
        const vendors = allowners.filter(item => !item.equals(userid))

对象 ID

 vendors = [
           "5d6caee9bb6f2921f45caf1b",
           "5d6dfcd6e3b11807944348b8",.....
           ]

用户架构

const userSchema = new mongoose.Schema({
name:{
    type: String,
    require: true,
    trim:true
})

const User = mongoose.model('User', userSchema)

我尝试了一个不起作用的 for 循环

   const vendorDetails = []
    for(let i=0; i<=vendors.length; i++)
        {
            vendorDetails[i] = User.find({_id:vendors[i]}) 
        }
        console.log(vendorDetails)

我期待的结果是这样的

   vendorDetails = [ { _id: 5d6caee9bb6f2921f45caf1b,
                    name: 'vithu'
                    },
                    {
                      _id: 5d6dfcd6e3b11807944348b8,
                    name: 'vcs'
                    }....]

【问题讨论】:

标签: node.js mongodb express mongoose


【解决方案1】:

试试这个

  db.collection.find( { _id : { $in : yourArrayOfIds } } );

【讨论】:

  • 我试过这个: const vendor = allowners.filter(item => !item.equals(userid));常量 vendorDetails = []; vendorDetails = User.find( { _id : { $in : vendor } } ) ; res.send(vendorDetails);结果:{}
  • 在查询中添加等待 vendorDetails = await User.find( { _id : { $in : vendor } } ) ;
  • 你需要等待这个,如果它对你有用,别忘了投票;)@vithushaji
  • 仍在获取 {} @AmirTahani vendorDetails = await User.find( { _id : { $in : vendor } } )
  • 您能检查一下是否有具有此 ID 的实际记录吗? @vithushaji
【解决方案2】:

在尝试推理您的代码时,请参见下面的示例。我希望这会有所帮助

async function getVendorDetails(ChatRoomModel, userObject = {}) {
    /* 
         Do your arguments verifications first (not included), then Await the result from User.find() 
         NOTE: I added "async" in front of the function in order to use "await"
         and injected the model into this function to keep it "pure", 
         you can implement this in other ways. Also pass a userObject containing
         your, well, user object :-)
    */
    const chatrooms = await ChatRoomModel.find({ owners: { $all: [userObject._id] } }); // chatrooms is expect to be an Array

    /* 
        Extract allOwners and vendor from the result {chatrooms}
        Note: I modified the variable name allowners -> allOwners
    */
    const allOwners = chatrooms.flatMap(room => room.owners); // allOwners is expected to be an Array

    /* 
        Changed the .equals() to a comparison operator
        Note: I modified the variable name in the filter function callback arg from item -> owner
    */
    const vendors = allOwners.filter(owner => owner !== userObject._id); // vendors is expected to be an Array

    try {
        // Await the result from User.find()
        const result = await User.find({
            _id: {
                $in: vendors
            }
        });
        // Return the result as a resolved promise
        return result;

    } catch (error) {
        // return error as a rejected promise
        return error;
    }
}

// Using the function

const ChatRoom = require('/path/to/model');

const user = {
    _id: '5d6caee9bb6f2921f45caf1b'
};


// Call the function (It returns a promise)

getVendorDetails(ChatRoom, user).then(result => {
    console.log(result);
}).catch((error) => {
    console.log(error);
});

【讨论】:

    猜你喜欢
    • 2019-09-08
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    相关资源
    最近更新 更多