猫鼬-可能的循环依赖关系? [英] mongoose - possible circular dependency?
问题描述
我的Express应用程序中有以下猫鼬模型:
I have the following mongoose models in my express app:
//user.js
var mongoose = require('mongoose');
var dog = require('./dog');
var userSchema = mongoose.Schema({
user: { type: String, required: true },
pass: { type: String, required: true },
dogs: [dog.dogSchema],
});
//dog.js
var mongoose = require('mongoose');
var dogSchema = exports.dogSchema = mongoose.Schema({
name: { type: String, required: true },
});
现在,从我的路线中,我正在这样创建一个新用户:
Now, from my routes I am creating a new user like this:
var user = require('../models/user');
var dog = require('../models/dog');
dog = new dog.Dog(dogData);
user = new user.User(data); //this will of course contain also dogData
user.save(next);
这是执行这种操作的正确方法吗?我觉得我可能会以某种方式生成循环依赖关系,无论如何我觉得它不正确.关于如何在另一个模型文件中创建架构的子文档的任何想法?
Is this the correct way to do this kind of operation? I have the feeling that I might be generating a circular dependency somehow, and anyway it does not look right to me. Any ideas on how to create sub-documents where the schema is from another model file?
推荐答案
您可以在两个方向上创建同时引用,而不会产生循环问题.使用ref
创建从一个文档到另一个文档的引用.从文档中:
You can create simultaneous references in two directions without creating circular problems. Create a reference from one document to the other using ref
. From the docs:
http://mongoosejs.com/docs/populate.html
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);
然后,您可以选择使用populate
Then you can then choose to load the sub document using populate
Story.find({ --your criteria-- })
.populate('_creator')
.exec(function (err, story) {../});
然后您可以将2个模式存储在单独的.js文件中,并require
两者都存储
You can then store the 2 schemas in separate .js files and require
them both
这篇关于猫鼬-可能的循环依赖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!