来自Node.js的MongoDB联接查询 [英] Mongodb join query from nodejs
本文介绍了来自Node.js的MongoDB联接查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 MongoDB 的新手,并试图将两个查询合并并将结果存储在一个模型中.我想在获取客户端任务时从另一个集合中获取客户端名称.
I am new to MongoDB and trying to join two query and store result in a single model. I want to fetch client name from another collection while fetching client task.
型号:-
const mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
const ClientTaskSchema = new mongoose.Schema({
clientId: {
type: Number
},
taskId: {
type: Number
},
clientTaskId: {
type: Number
},
active: {
type: Boolean
}
});
module.exports = mongoose.model('ClientTask', ClientTaskSchema);
控制器:-
module.exports.getClientByTask = function(req, res) {
var query = url.parse(req.url,true).query;
ClientTask.find({taskId: query.taskId}, function(err, clientTask) {
if (err) throw err;
if (!clientTask) {
res.status(200).json({ success: false, message: 'Somthing went wrong. Please contact admin.'});
}
else {
res.status(200).json({ success: true, message: 'Successfull', data: clientTask});
}
});
};
推荐答案
一种选择是通过clientId
作为参考:
One option is to pass clientId
as a reference:
clientId: {
type: mongoose.Schema.Types.ObjectId, ref: 'Client / or whatever your model'
}
然后,您将能够使用Mongoose的populate
方法 http://mongoosejs.com/docs/populate.html
Then you'll be able to use Mongoose's populate
method http://mongoosejs.com/docs/populate.html
ClientTask
.find({ taskId: query.taskId })
.populate('clientId', { name: 1 }).exec(function (err, clientTask) {
if (!clientTask) {
res.status(404).json({ message: 'Client task not found' })
}
// your logic
});
这篇关于来自Node.js的MongoDB联接查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文