0
私はmongooseで基本的なスキーマ継承を実装しようとしました。 http://mongoosejs.com/docs/api.html#model_Model.discriminatorおよびhttps://github.com/Automattic/mongoose/pull/1647およびInheriting Mongoose schemasに基づく。"Base schema"は2(mongodb - mongoose)の代わりに1つの型だけを返します
Personに対して.find()を実行しようとすると、従業員が私に戻ってくるだけです。私は従業員とボランティアを期待しているので、私にとっては問題です。
スキーマ:私はボランティアや従業員を取得しようとどのように
var mongoose = require('mongoose');
var util = require('util');
var Schema = mongoose.Schema;
function BaseSchema() {
Schema.apply(this, arguments);
this.add({
firstname: String,
lastname: String,
created_at: Date,
updated_at: { type: Date, default: Date.now }
});
}
util.inherits(BaseSchema, Schema);
var PersonSchema = new BaseSchema();
var EmployeeSchema = new BaseSchema();
EmployeeSchema.add({department: String});
var VolunteerSchema = new BaseSchema();
VolunteerSchema.add({shop: String});
var Person = mongoose.model('Person', PersonSchema);
var Volunteer = Person.discriminator('volunteer', VolunteerSchema);
var Employee = Person.discriminator('employee', EmployeeSchema);
module.exports = mongoose.model('Volunteer', VolunteerSchema);
module.exports = mongoose.model('Employee', EmployeeSchema);
:私はすべてのリード/手がかりのために '備品'
var mongoose = require('mongoose'),
Person = require('../models/person.js'),
Employee = mongoose.model('Employee'),
Volunteer = mongoose.model('Volunteer');
var db = mongoose.connect('mongodb://127.0.0.1:27017/dbname')
.then(function() {
console.log('connection to db successful');
})
.catch(function(err) {
console.log(err);
});
Employee.create([
{
firstname: 'John',
lastname: 'Steinbeck',
department: 'Deprimos',
created_at: Date.Now
}, {
firstname: 'Terry',
lastname: 'Pratchett',
department: 'Fun',
created_at: Date.Now
}, {
firstname: 'Frank',
lastname: 'Herbert',
department: 'Mindblowing',
created_at: Date.Now
}, {
firstname: 'George R.R.',
lastname: 'Martin',
department: 'Sadistic',
created_at: Date.Now
}
], function(err, person) {
if (err) console.log(err);
else console.log(person);
});
Volunteer.create([
{
firstname: 'Zekiya',
lastname: 'Orson',
shop: 'Shop 1',
created_at: Date.Now
}, {
firstname: 'Gazorp',
lastname: 'Azorp',
shop: 'Shop 2',
created_at: Date.Now
}
], function(err, person) {
if (err) console.log(err);
else console.log(person);
});
感謝を追加する方法
var express = require('express'),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
Person = require('../models/person.js');
// ...
router.get('/', function(req, res, next) {
Person.find({}, function (err, persons) {
if (err) return next(err);
res.json(persons);
});
});
/ソリューション:)