如何在猫鼬中填充数据而不更改当前架构

时间:2018-07-11 07:54:44

标签: javascript mongodb mongoose

我已经为猫鼬创建了两个架构,分别命名为associates和outlet。 插座架构:-

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var OutletSchema = new Schema(
{
  associate_id: {type: ObjectId, max: 100 },
  city_id:{type:ObjectId, max: 100},
  outlet_name: {type: String, max: 100},
  oulet_address: {type: String, max: 500},
  outlet_contact: {type: String, minlength: 9, maxlength: 12 },
  active: {type: Boolean}`enter code here`
}`
);

module.exports = mongoose.model('Outlet', OutletSchema);

关联模式:-

var mongoose = require('mongoose');

var Schema = mongoose.Schema;
ObjectId = Schema.ObjectId;

var AssociateSchema = new Schema(
{

  associate_name: {type: String, max: 100},
  associate_address: {type: String, max: 500},
  associate_contact: {type: String, minlength: 9, maxlength: 12 },
  associate_email: {type: String, max: 100},
  active: {type: Boolean}
}
);

module.exports = mongoose.model('Associate', AssociateSchema);

这些是我创建的模式。

如何使用Relationship()填充同事的插座

我尝试了下面给出的这段代码。

router.get('/getUsingPopulate', function (req, res) {
    data = {}
    Associate.relationship({path:'outlet', ref:'Outlet',refPath:'associate_id'})
    Outlet.find({}).populate('Associate').exec()
    .then(function(alldata){
        console.log(alldata)

    })


})

关联数据库:-

_id: 5b40428088e5f0187dedb342
category_id: 5b34a99709d3ff3e2b5a399c
associate_name: "Cafe Coffee Day"
associate_address: "Coffee day kormangala"
associate_contact: "989545458645"
associate_email: "ccdkor@yahoo.com"
active: true
__v: 0

插座数据库:-

_id: 5b4471f4c5bf8018409c7c64
associate_id: 5b40428088e5f0187dedb342
city_id: 5b3c49fee0de9210a60a2266
outlet_name: "Coffee Day Whitefield"
oulet_address: " Coffee Day Whitefield"
outlet_contact: "7587454478"
active: true
__v:0

期望的输出:-

  {
   "_id": "5b40428088e5f0187dedb342",
   "name": "Cafe Coffee Day",
   "outlets": [
     {
       "_id": "5b4471f4c5bf8018409c7c64",
       "associate_id": 5b40428088e5f0187dedb342,
       "name": "Coffee Day Whitefield",

     }]

1 个答案:

答案 0 :(得分:0)

我使用以下代码得到了答案:-

插座模式已更改为:-

var OutletSchema = new Schema(
{
  associate_id: {type: Schema.Types.ObjectId, ref: 'Associate'  },
  city_id:{type:ObjectId, max: 100},
  outlet_name: {type: String, max: 100},
  oulet_address: {type: String, max: 500},
  outlet_contact: {type: String, minlength: 9, maxlength: 12 },
  active: {type: Boolean}
})

我给出的填充代码是:-

Deal.find({..}).populate({
                                path: 'outlet_id',
                                model: 'Outlet',
                                populate: {
                                  path: 'associate_id',
                                  model: 'Associate'
                                }
                              }).exec()

感谢大家的支持。