我的快递应用程序中有以下猫鼬模型:
//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 },
});
现在,从我的路线开始,我正在创建一个像这样的新用户:
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);
这是进行此类操作的正确方法吗?我觉得我可能会以某种方式产生循环依赖,无论如何它对我来说都不合适。关于如何创建模式来自另一个模型文件的子文档的任何想法?
答案 0 :(得分:3)
您可以在两个方向上创建同时参考,而不会产生循环问题。使用ref
创建从一个文档到另一个文档的引用。来自文档:
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
Story.find({ --your criteria-- })
.populate('_creator')
.exec(function (err, story) {../});
然后,您可以将2个架构存储在单独的.js文件中,并require
将它们都存储在