无法插入填充文件w / mongoose?

时间:2015-10-19 02:02:36

标签: node.js mongodb mongoose

我正在尝试使用带有正确数据的引用文档填充文档字段并将其保存到数据库中。但是,即使我已成功保存文档,我也无法在数据库中正确插入文档。

 **getting-started.js**

 ...
 var personSchema = mongoose.Schema({
  _id     : Number,
  name    : String,
  age     : Number,
  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
  });

  var storySchema = mongoose.Schema({
   _creator : { type: Number, ref: 'Person' },
   title    : String,
   fans     : [{ type: Number, ref: 'Person' }]
  });

var Story  = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);


var Johns = new Person({ _id: 15, name: 'Johns', age: 154});
Johns.save(function (err) {
if (err)  {
  console.log('Person Save error! %s', err);
}

var story1 = new Story({
  title: "Once upon a timex??",
  _creator: Johns._id    // assign the _id from the person
 });

story1.save(function (err) {
   if (err) return handleError(err);
   console.log('successful story save! %d', story1._creator);
 });

});

Story
.find({ title: 'Once upon a timex@@@@@@' })
.populate('_creator')
.exec(function (err, story) {
  if (err) return handleError(err);
  console.log("callback story: ", story);

 story.save(function (err, story) {

   if (err) return console.error(err);
    console.log('successful save new story w/ populated _creator');
    console.log('The story: creators name: %s', story._creator.name);
    console.log('The story: creator field: %s', story._creator);

  })

});

第一次执行:

>>node getting-started.js

关注输出:

>>opened conn to db
successful story save! 15
opened conn to db
{ fans: [],
   __v: 0,
   _creator: { stories: [], __v: 0, age: 154, name: 'Johns', _id: 15 },
   title: 'Once upon a timex@@@@@@',
   _id: 56244cf796f73380353e803a }
   successful save new story w/ populated _creator
   The story: creators name: Johns
   The story: creator field: { stories: [], __v: 0, age: 154, name: 'Johns',              _id: 15 }

然而,在评论出以下代码后:

var Johns = new Person({ _id: 15, name: 'Johns', age: 154});
    Johns.save(function (err) {
    if (err)  {
      console.log('Person Save error! %s', err);
    }

    var story1 = new Story({
      title: "Once upon a timex??",
      _creator: Johns._id    // assign the _id from the person
     });

    story1.save(function (err) {
       if (err) return handleError(err);
       console.log('successful story save! %d', story1._creator);
     });

    });

下次我正在执行

Story
    .find({ title: 'Once upon a timex@@@@@@' })
    .exec(function (err, story) {
      if (err) return handleError(err);
      console.log("callback story: ", story);
    });

我无法在_creator的填充字段中看到我保存的故事,它仍然只有人_id而不是person对象:

{ fans: [],
  __v: 0,
  _creator: 15,
  title: 'Once upon a timex@@@@@@'
  _id: 56244cf796f73380353e803a }

0 个答案:

没有答案