Mongo参考模式集合

时间:2015-09-29 02:28:18

标签: mongodb mongoose

我希望确认我的收藏结构能够正确地允许我在我的收藏品之间进行参考。理想情况下,我有一个标记为category的父集合,其中子集合标记为images。我计划为我的“类别”集合提供大约4个文档,为我的“图像”提供30个文档。所有文档都将使用csv文件格式从命令行上传。如果我像下面那样设置我的模式并上传带有与模式中的字段匹配的标题的文档,那么参考点是否会出现问题?

分类

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

var categorySchema = new Schema({
    name: String,
    description: String
});

var Category = mongoose.model(‘Category’, categorySchema);

module.exports = Category;

图片

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

var imageSchema = new Schema({
    imageUrl: String,
    category_id: { type: sechema.ObjectId, ref:"categorySchema"}
});

var Images = mongoose.model('Images', imageSchema);

module.exports = Images;

这是我的.csv文件的布局

category.csv

**name**  **description**

Drama Stories about...

images.csv

**imageUrl**               **category_id**

www.site.com/image.jpg       Drama

1 个答案:

答案 0 :(得分:1)

希望只有一个category属于image。一个category有多个images,每个图片belongs只有一个category

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

var categorySchema = new Schema({
    name: String,
    description: String
    images: [{type: mongoose.Schema.Types.ObjectId, ref: 'Images'}]
});

var Category = mongoose.model(‘Category’, categorySchema);

module.exports = Category;

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

var imageSchema = new Schema({
    imageUrl: String,
    category_id: {type: mongoose.Schema.Types.ObjectId, ref:"Category"}
});

var Images = mongoose.model('Images', imageSchema);

module.exports = Images;

注意:您可以引用model而不是Schema

然后,您可以使用mongoose middleware在保存时更新参考文献。

imageSchema.pre('save', function(next){
    var Category = require("../models/Category");
    var image = this;
    Category.findOneAndUpdate(
        {_id: {$in: {this.category_id}},
        {$push: {images: this._id}},
        next
    );
});