我是MongoDB的新手,并尝试将两个查询合并并将结果存储在一个模型中。我想在获取客户端任务时从另一个集合中获取客户端名称。

模型:-

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作为参考:

clientId: {
 type: mongoose.Schema.Types.ObjectId, ref: 'Client / or whatever your model'
}


然后,您将能够使用猫鼬的populate方法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
});

07-26 09:43
查看更多