如何成功填充mongoose模式

时间:2017-05-25 08:12:20

标签: javascript node.js mongodb express

我有一个人物模型

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

const PersonSchema = new Schema({
name: String,
cars: [{
    type: Schema.types.ObjectId,
    ref: 'Cars'
    }]
  });

const Person = module.exports = mongoose.model('Person', PersonSchema);

我有一个汽车模型

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

const CarsSchema = new Schema({
color: String,
owner: {
    type: Schema.Types.ObjectId,
    ref: 'Person'
},
});

const Cars = module.exports = mongoose.model('Cars', CarsSchema);

如何确保每次添加汽车时都会列入特定人员的汽车阵列?

现在,我做过类似的事情:

  const newPerson = new Person({
    name: 'jared'
  });

  newPerson.save()
    .then(person => {
      console.log(person);
    });

  const newCar = new Car({
    color: 'red'
  });

  newCar.save(function(err, car) {
    if (err) {
      console.log(err)
    } else {
      car.populate(
        car, {
          path: "owner"
        },
        function(err, car) {
          if (err) {
            console.log(err);
          } else {
            console.log(car);
          }
        });
    }
  });

代码可以正常运行,并且可以通过" jared"将汽车正确打印到终端。看到占用所有者字段的人员文档,但结果未保存到MongoDB。相反,当我检查MongoDB时,我只看到只有" jared" document _id占据所有者字段。谁能告诉我为什么会这样?

1 个答案:

答案 0 :(得分:0)

您必须将_id中的person分配给car owner

let newPerson = new Person({
  name: 'jared'
});

newPerson.save()
  .then(person => {
    console.log(person);

    let newCar = new Car({
      color: 'red',
      owner: person._id
    });

    newCar.save(function(err, car) {
      if (err) {
        console.log(err)
      } else {
        car.populate(
          car, {
            path: "owner"
          },
          function(err, car) {
            if (err) {
              console.log(err);
            } else {
              console.log(car);
            }
          });
      }
    })
  });