【问题标题】:How to get another colletion data with mongoose populate如何使用猫鼬填充获取另一个集合数据
【发布时间】:2019-01-07 20:49:21
【问题描述】:

我在节点 js 中有以下模型,我想在一次调用中从文件架构和客户端架构中获取数据,我正在阅读有关填充但不知道如何使用它。

这是我的模特

 const mongoose = require('mongoose');

const fileSchema = mongoose.Schema({
    _id: mongoose.SchemaTypes.ObjectId,
    client_id: mongoose.SchemaTypes.ObjectId,
    user_id: mongoose.SchemaTypes.ObjectId,
    status: String,
    name: String,
    path: String,
    clients: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Client' }]
});

const clientSchema = mongoose.Schema({
    _id: mongoose.SchemaTypes.ObjectId,
    name: String,
    img: String
});


module.exports =
    mongoose.model('File', fileSchema, 'files'),
    Client = mongoose.model('Client', clientSchema, 'clientes');

这就是我现在获取文件数据的方式

exports.getFiles = (req, res, next) => {
    File.find({ field: res.locals.field })
    .select('_id client_id user_id status name path')
    .exec()
    .then(file => {
        res.status(200).json({
            response: file
        });
    })
    .catch(err => {
        console.log(err);
        res.status('500').json({
            error: err
        });
    });
};

这会返回一个 json 响应,当我尝试使用填充时,我得到了一个空数组。

【问题讨论】:

    标签: node.js mongoose mongoose-populate


    【解决方案1】:

    您快到了,但您的查找搜索有问题。至少对于您发布的文件模型,您没有名为“字段”的字段,因此您不会得到任何结果。

    假设您正在尝试根据文件名查找文件,并且请求被发送到 url 'blah/files/:name' 并且看起来您正在使用 Express.js,所以这应该工作。

    要使用填充,您通常执行以下操作:

    File.find({ name: req.params.name })
        .populate('clients')
        .exec()
        .then(files => {
            res.status(200).json({
                response: files
            });
        })
        .catch(err => {
            console.log(err);
            res.status('500').json({
                error: err
            });
        });
    

    您的“选择”位中的内容没有必要,因为您是根据文件模型开始搜索的,而您只是要求它返回您在该模型上拥有的所有字段。您可以“免费”获得结果中返回的内容。

    由于您在文件模型中指定它是引用客户端模型的对象 ID,因此填充在“客户端”字段中被标记出来。 Mongoose 应该基本上自动处理它。但是,请注意,客户端模型上的所有字段都将填充到文件的客户端数组中。如果您只想为您的客户返回一个或几个字段,那么您应该使用 select。

    另外注意:find 方法将返回一个数组,即使它只是一个文档的结果。如果您期望或只想要一个结果,请改用 findOne 方法。

    更新

    您的模型文件中的模块导出中似乎还有一个 bugaboo,这可能就是您遇到问题的原因。我的编码风格与你的不同,但我会这样做只是为了确保没有混乱:

    const File = mongoose.model('File', fileSchema);
    const Client = mongoose.model('Client', clientSchema);
    
    module.exports = { File, Client };
    

    然后在您的路由器代码中,您将它们导入:

    const { File, Client } = require('<path-to-model-file>');
    

    【讨论】:

    • 感谢您的回答,我是一个带有节点的 api 初学者,响应仍然是一个带有我的文件数据的 json 和一个名为 clientes 的字段,其中包含一个空数组,我认为这是因为我的发现,什么我需要准确地找到我的客户数据?
    • 如果不知道您如何设置 API 以及您在哪个字段上进行搜索,我无法真正回答这个问题。您能否使用您正在使用的 url 和 get 函数更新您的原始问题?
    • 我更新了我原来的答案,因为我之前没有注意到你的 module.exports 表达式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 2017-01-15
    • 1970-01-01
    • 2021-06-03
    • 2017-10-11
    • 2017-01-23
    • 2021-08-04
    相关资源
    最近更新 更多