Mongoose:如何使用ObjectId链接模型?

时间:2018-03-12 21:57:29

标签: express mongoose

我正在使用Express,Mongoose和Mongodb。我有两个模型,一个用于User,另一个用于Review,如下所示:

var User =  mongoose.Schema({

  firstName:String,
  lastName: String,
  email: String
});
mongoose.model('User', User);

var Review =  mongoose.Schema({

  foodRating:Number,
  serviceRating: Number,
  locationRating: Number,
  wouldReturn: boolean,

});
mongoose.model('Review', Review);

我想以评论属于用户的方式链接两个模型。

我读到了关于ObjectId的内容,但目前尚不清楚如何实现它。我应该创建它,然后使用它,如下所示:

const MyObjectId = mongoose.Types.ObjectId;

然后覆盖我想用它链接到我的第一个模型的模型的_id?

var User =  mongoose.Schema({

      firstName:String,
      lastName: String,
      email: String,
     review: [MyObjectId] // retrieves model below from its _id:MyObjectId

    });
    mongoose.model('User', User);

    var Review =  mongoose.Schema({
      _id: MyObjectId, // overriding _id with ObjectId
      foodRating:Number,
      serviceRating: Number,
      locationRating: Number,
      wouldReturn: boolean,

    });
    mongoose.model('Review', Review);

这是对的吗?或者我该怎么做?

1 个答案:

答案 0 :(得分:1)

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

中查看此内容

基本上,你想要做的是:

const MyObjectId = mongoose.Types.ObjectId;

var User =  mongoose.Schema({

    firstName:String,
    lastName: String,
    email: String,
    review: [MyObjectId] // retrieves model below from its _id:MyObjectId
});

mongoose.model('User', User);

var Review =  mongoose.Schema({
    user: { type: MyObjectId, ref: 'User' } // overriding _id with ObjectId
    foodRating: Number,
    serviceRating: Number,
    locationRating: Number,
    wouldReturn: boolean,

});
mongoose.model('Review', Review);

完成后,“用户”文档中的_id将存储在“审阅”文档的用户字段中。然后你可以做这样的事情:

Review.
    findOne({ foodRating: 4 }).
    populate('user').
    exec((err, review) => {
      if (err) return handleError(err);
      console.log('The user is %s %s', review.user.firstName, review.userLastName);
      // prints "The user is So-and-so"
    });