如何使用猫鼬填充获取另一次搜集数据

时间:2019-01-04 16:33:38

标签: node.js mongoose mongoose-populate

我在node 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响应,我得到了一个空数组。

1 个答案:

答案 0 :(得分:0)

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

假设您试图根据文件名查找文件,并且该请求已发送到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,因此在“客户机”字段上标记了填充项。猫鼬应该基本上自动地处理它。但是,请注意,客户端模型上的所有字段都将填充在文件的客户端数组中。如果您只想为客户返回一个或几个字段,则应在此处使用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>');
相关问题