简体   繁体   English

如何在文档属性(数组)中查找 ID 并返回该 object 的填充信息

[英]How to find an ID inside a document property (array) and return the populated information of that object

I have the following document in MongoDB.我在 MongoDB 中有以下文档。 How can I find a specific ID inside the likes array and return the populated information of that object?如何在 likes 数组中找到特定 ID 并返回该 object 的填充信息?

This is the document:这是文件:

 { _id: ObjectId("60a90f0e1f4af802e8b893e6"), status: 'Available', likes: [ ObjectId("60a8e0b9baa1572b847931ed"), ObjectId("60aa342cb6b39e3024453465") ], name: 'coba', age: '1 Year', __v: 0 }

This is the function I have tried but it's returning a 404 error, though as you can see the id actually exists in the likes array.这是我尝试过的 function 但它返回 404 错误,尽管您可以看到 id 实际上存在于 likes 数组中。

 const [foundUser] = await PetsModel.find( { likes: { $in: ["60a8e0b9baa1572b847931ed"] } }, { likes: 1 } ).populate({ path: 'likes', select: { __v: 0, createdAt: 0, updatedAt: 0, password: 0 } }); res.status(201).json({ success: true, data: foundUser.likes });

There you are telling MongoDB to search a string, not an id.在那里,您告诉 MongoDB 搜索字符串,而不是 id。 So you have to convert the string into an id so MongoDB can search it.因此,您必须将字符串转换为 id,以便 MongoDB 可以搜索它。 The code should look like this:代码应如下所示:

const mongoose = require('mongoose');

const [foundUser] = await PetsModel.find(
      {
        likes: { $in: [ mongoose.Types.ObjectId("60a8e0b9baa1572b847931ed") ] }
      },
      { likes: 1 }
    ).populate({
      path: 'likes',
      select: {
        __v: 0,
        createdAt: 0,
        updatedAt: 0,
        password: 0
      }
    });

    res.status(201).json({
      success: true,
      data: foundUser.likes
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM