两个集合mongodb之间的关系

时间:2016-05-08 14:57:40

标签: javascript node.js mongodb express mongoose

我的mongodb基地有2个收藏:分类和书籍

category.js

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var categoryModel = new Schema({
  catName: String,
  menuKey: String
});
module.exports = mongoose.model('Category', categoryModel);

和book.js

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var bookModel = new Schema({
  title: String,
  author: String,
  category: String ,
  summary: String ,
  cover: String ,
  price: Number,
  qte: Number,
});
module.exports = mongoose.model('book', bookModel);

可以添加:

  

var category = require(' ./ category.js')

并重新开始这一行:

  

category:String,

通过

  

类别:[类别],

3 个答案:

答案 0 :(得分:4)

这是满足您要求的解决方案。

//category.js
    var mongoose = require("mongoose");
    var Schema = mongoose.Schema;
    var categoryModel = new Schema({
      catName: String,
      menuKey: String
    });
    module.exports = mongoose.model('Category', categoryModel);

    //book.js
    var mongoose = require("mongoose");
    var Schema = mongoose.Schema;
    var bookModel = new Schema({
      title: String,
      author: String,
      category: [{ type: Schema.Types.ObjectId, ref: 'Category' }],
      summary: String ,
      cover: String ,
      price: Number,
      qte: Number,
    });
    module.exports = mongoose.model('book', bookModel);

答案 1 :(得分:2)

category: {type: mongoose.Schema.Types.ObjectId, ref: 'Category'}

答案 2 :(得分:2)

你不想这样做。您想使用ref关键字指明关系,您可以在其中引用另一个集合中的Schema.ObjectId

来自mongoose的official populate文档:

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

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

var storySchema = 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);

在您的情况下,您的Book模型引用了Category