如何在JavaScript中使用.populate()

发布于 2025-02-05 13:17:14 字数 529 浏览 5 评论 0 原文

的集合

CR

我有一个名为“我想做的事情”

let cre = await CR.find({myid: "xxxxxx"})

就是这样查询:而且我还有一个称为 cla 的集合,但是我需要根据 cre /代码>。 CRE的结果将返回一个class_id,在其中我需要用来查询 cla 集合以查找 _id 。在所有这些结束时,我想理想地合并两者,我相信您可以通过 .populate()进行操作,然后将其发送到Teh前端。

我已经尝试过:

 let cre = await cr.find({myid: "xxx"}).populate('loc').populate('desc').populate('dt');

但这不起作用。我该如何解决?

I have a collection called

CR

what I want to do is query CR like so:

let cre = await CR.find({myid: "xxxxxx"})

and i also have a collection called cla, but that one i need to query based off of the results of cre. The results of cre will return a class_id, in which I need to use to query the cla collection to find the _id. At the end of all of this, I want to ideally merge the two, which I believe you can do through .populate(), and then send it to teh front-end as one.;

I have tried this:

 let cre = await cr.find({myid: "xxx"}).populate('loc').populate('desc').populate('dt');

but this isn't working. how can I fix this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

桃扇骨 2025-02-12 13:17:14

这可能是由于图式造成的,但这是干净且易于使用的方式。

 let cre = await cr.find({myid: "xxx"}).populate(['loc','desc','dt']);

It may be due to schemas, but this is how it's clean and simple to use;

 let cre = await cr.find({myid: "xxx"}).populate(['loc','desc','dt']);

旧瑾黎汐 2025-02-12 13:17:14

首先,您可以在 cr 收集模式中采用 cla 收集“ _id”。在 cr 集合的模式中,请参阅 cla模型ID

const creSchema = mongoose.Schema({
    name: String,
    classnId: { type: mongoose.Types.ObjectId, ref: "Cla" }
});

然后您可以像这样填充,

const cres = await CR.find({}).populate({path:'classnId', select:'columnName'});

希望这将解决您的问题。

注意:在填充时,您可以按空格给出多个列名,如果您在这样的列名之前给出负名(-columnname),那么该列将无法显示何时调用API。

Firstly, you can take cla collection "_id" in CR collection schema. In schema of CR collection refer to cla model id like this,

const creSchema = mongoose.Schema({
    name: String,
    classnId: { type: mongoose.Types.ObjectId, ref: "Cla" }
});

Then you can populate like,

const cres = await CR.find({}).populate({path:'classnId', select:'columnName'});

Hopefully, this will solve your issue.

Note: There in populating you can give multiple column names by space and if you give a minus before a column name like this (-columnName) then that column will not show when you will call the API.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文