如何使用Mongoose populate存储ObjectId以外的数据?

时间:2012-05-21 05:36:54

标签: mongodb mongoose

以此为例

http://mongoosejs.com/docs/populate.html

如果我尝试调整它以便'粉丝'也包含评级

var db = require('houselib/db');
var Schema = db.Schema;
var mongoose = db.mongoose;

var PersonSchema = new Schema({
    name    : String
    , age     : Number
    , stories : [{ type: Schema.ObjectId, ref: 'Story' }]
});

var StorySchema = new Schema({
    _creator : { type: Schema.ObjectId, ref: 'Person' }
    , title    : String
    , fans     : [{ type: Schema.ObjectId, ref: 'Person', rating: Number}]
});

var Story  = mongoose.model('Story', StorySchema);
var Person = mongoose.model('Person', PersonSchema);

var aaron = new Person({ name: 'Aaron', age: 100 });

aaron.save(function (err) {
    if (err) throw err;

  var story1 = new Story({
      title: "A man who cooked Nintendo"
    , _creator: aaron._id
    , fans: [{type: aaron._id, rating: 4}]
  });

  story1.save(function (err) {
    if (err) throw err;
        Story
        .find({ _creator: aaron._id })
        .populate('_creator') // <-- not really necessary
        .run(function (err, stories) {
            if (err) throw err;
            console.log('The stories JSON is an array: ', stories);
        })
  });

})

我收到以下错误

  

CastError:对于值“[object Object]”

,强制转换为未定义失败

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

story.fans是一系列目标。 objectids做不了评级。您需要将评级添加到Person模式而不是故事模式。

var PersonSchema = new Schema({
    name    : String
    , age     : Number
    , rating: Number
    , stories : [{ type: Schema.ObjectId, ref: 'Story' }]
});