如何访问已保存在其他相关模型中的信息.MongoDB, NodeJS.



我在这方面真的很新,我想练习查询并尝试进行一个非常不同的练习,但它并没有像我预期的那样进行。

我有三个模型:

const userSchema = new Schema({
info1: String,
info2: String,
},

const serviceSchema = new Schema(
{
name: String,
legalOwner: {
type: Schema.Types.ObjectId,
ref: 'User',
},
},

const orderSchema = new Schema(
{
client: { type: Schema.Types.ObjectId, ref: 'User' },
service: { type: Schema.Types.ObjectId, ref: 'Service' },
description: String
},

我的用户可以像合法所有者或客户一样行事。我想显示用户之前设置为合法所有者的信息。这已经保存在Mongo中,我如何访问该数据,是否有查询?我需要在我的模型订单中设置它吗?

const orderSchema = new Schema(
{
client: { type: Schema.Types.ObjectId, ref: 'User' },
service: { type: Schema.Types.ObjectId, ref: 'Service' },
description: String,
legalOwner: { type: Schema.Types.ObjectId, ref: 'Service' },
},

我在这个查询上尝试了很多东西。但是没有任何效果...

await Order.findById(id).populate('service')
据我所知,

ObjectId 存储在 mongoDb 中,_id。

试试这个

const query = { _id: new ObjectID(id)};
await Order.findOne(query).populate('service')

同时从 mongodb 导入 ObjectID node_module 作为

import { ObjectID } from 'mongodb';

最新更新