question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Discriminators is not working

See original GitHub issue

app.js

const feathers = require('feathers');
const errorHandler = require('feathers-errors/handler');
const rest = require('feathers-rest');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const service = require('feathers-mongoose');
const Post = require('./post');
const Model = require('./message-model');

// Tell mongoose to use native promises
// See http://mongoosejs.com/docs/promises.html
mongoose.Promise = global.Promise;

// Connect to your MongoDB instance(s)
mongoose.connect('mongodb://localhost:27017/feathers');

// Create a feathers instance.
const app = feathers()
  // Enable REST services
  .configure(rest())
  // Turn on JSON parser for REST services
  .use(bodyParser.json())
  // Turn on URL-encoded parser for REST services
  .use(bodyParser.urlencoded({ extended: true }))
  // Connect to the db, create and register a Feathers service.
  .use('/messages', service({
    Model,
    lean: true, // set to false if you want Mongoose documents returned
    paginate: {
      default: 2,
      max: 4
    }
  }))
  .use(errorHandler());

// Create a dummy Message
// app.service('messages').create({
//   text: 'Message created on server'
// }).then(function (message) {
//   console.log('Created message', message);
// });
var options = {
  discriminatorKey: '_type'
};

var TextPostSchema = new mongoose.Schema({
  text: { type: String, default: null }
}, options);

TextPostSchema.index({'updatedAt': -1, background: true});

// Note the use of `Post.discriminator` rather than `mongoose.discriminator`.
const TextPost = Post.discriminator('text', TextPostSchema);

// Using the discriminators option, let feathers know about any inherited models you may have
// for that service
app.use('/posts', service({
  Model: Post,
  discriminators: [TextPost]
}));

app.service('posts').create({
  text: 'Message created on server'
}).then(function (message) {
  console.log('Created message', message);
});

// Start the server.
const port = 3030;
app.listen(port, () => {
  console.log(`Feathers server listening on port ${port}`);
});

post.js

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

var options = {
  discriminatorKey: '_type'
};

var PostSchema = new Schema({
  createdAt: { type: Date, 'default': Date.now },
  updatedAt: { type: Date, 'default': Date.now }
}, options);

PostSchema.index({ 'updatedAt': -1, background: true });

var PostModel = mongoose.model('Post', PostSchema);

module.exports = PostModel;

message-model.js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;
const MessageSchema = new Schema({
  text: {
    type: String,
    required: true
  }
});
const Model = mongoose.model('Message', MessageSchema);

module.exports = Model;

Results:

use feathers switched to db feathers show collections posts db.posts.find({}); { “_id” : ObjectId(“590b0de0b4c4db53d6fe27d5”), “updatedAt” : ISODate(“2017-05-04T11:17:52.947Z”), “createdAt” : ISODate(“2017-05-04T11:17:52.947Z”), “__v” : 0 }

Question is: I expected that, there is a field name “text” when i run db.posts.find({});. But i follow by guide line, it’s not work. Please help me

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:6 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
victorm95commented, Jul 5, 2017

I don’t know if you already figured this out, but you must also send the discriminatorKey (in this case _type).

app.service('posts').create({
  _type: 'text',
  text: 'Message created on server'
});
1reaction
marshallswaincommented, May 4, 2017

@dattq6 please wrap all code blocks in fences (trip back ticks). You can also get highlighting by doing ```js on the opening code block.

```js
// insert code here
```
Read more comments on GitHub >

github_iconTop Results From Across the Web

Why are discriminators not supported for AllOf ? #666 - GitHub
Hello, I have an OpenAPI Schema that uses inheritance like this. ViewConnectionNoRelationship: type: object additionalProperties: false ...
Read more >
Mongoose pre save is not running with discriminators
AFAIK hooks need to be added to your schema before compiling your model, hence this won't work. You can, however, first create the...
Read more >
Solved: Error with discriminator - SmartBear Community
Solved: I'm trying to create an OpenAPI specification with a body with a discriminator field and two models, using oneOf.
Read more >
Mongoose v6.8.2: Discriminators
Discriminators are a schema inheritance mechanism. They enable you to have multiple models with overlapping schemas on top of the same underlying MongoDB ......
Read more >
Problem with logging discriminator not working
I thought I had it right but it's not looking that way. Here is the code I am using: logging discriminator dropsec mnemonics...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found