GithubHelp home page GithubHelp logo

jkheadley / rest-hapi Goto Github PK

View Code? Open in Web Editor NEW
1.2K 41.0 153.0 7.05 MB

πŸš€ A RESTful API generator for Node.js

Home Page: https://resthapi.com

License: MIT License

JavaScript 99.35% Shell 0.01% CSS 0.65%
hapi hapi-plugin joi swagger rest rest-api validation crud mongoose mongodb

rest-hapi's Introduction

rest-hapi logo


rest-hapi title

A RESTful API generator rest-hapi tweet

rest-hapi is a hapi plugin that generates RESTful API endpoints based on mongoose schemas. It provides a powerful combination of relational structure with NoSQL flexibility. You define your data models and the rest is done for you. Have your API up and running in minutes!

Features


Live demo

rest-hapi-demo-optimized

View the swagger docs for the live demo:

https://demo.resthapi.com

Or, for a more complete example, check out the appy api:

https://api.appyapp.io

Documentation

Check out the docs on the official site!

Requirements

You need Node.js installed and you'll need MongoDB installed and running.

Quick Start

rest-hapi-demo-alt-optimized

(NOTE: For an alternative quick start, check out his awesome yeoman generator for rest-hapi.)

  1. Clone the demo repo
$ git clone https://github.com/JKHeadley/rest-hapi-demo.git
$ cd rest-hapi-demo
  1. Install the dependencies
$ npm install
  1. Seed the models
$ ./node_modules/.bin/rest-hapi-cli seed
  1. Start the server
$ npm start
  1. View the API docs at

http://localhost:8080/

...have fun!

Example Projects

appy: A boilerplate web app.

rest-hapi-demo: A simple demo project implementing rest-hapi in a hapi server.

Contributing

We welcome contributions to rest-hapi! These are the many ways you can help:

Please read our contribution guide to get started. Also note that this project is released with a Contributor Code of Conduct, please make sure to review and follow it.

Contributors

Thanks goes to each one of our contributors! πŸ™

Become a contributor.

Backers

Support us with a monthly donation and help us continue our activities! Become a backer.

Questions?

If you have any questions/issues/feature requests, please feel free to open an issue. We'd love to hear from you!

Support

Like this project? Please star it!

License

rest-hapi is licensed under a MIT License.

rest-hapi's People

Contributors

1change avatar asterion avatar dashawk avatar davad avatar dependabot[bot] avatar drphelps avatar gitter-badger avatar hilanmiao avatar jkheadley avatar johnhillegass avatar kpfromer avatar li5tun avatar lucarp avatar mkg20001 avatar moacirosa avatar newnok6 avatar okoyl avatar shiva avatar sukantgujar avatar tamias avatar thiagoarioli avatar yoieh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rest-hapi's Issues

Boom.serverTimeout is not a function

error-helper.js calls Boom.serverTimeout, but Boom doesn't define that method. Which HTTP error is intended for these cases? Perhaps Boom.badImplementation, which corresponds to HTTP 500 Internal Server Error?

How to do some enhancement or changes in existing API created automatically by Rest-Hapi.

Hi,
First of all thanks for providing awesome module like rest-hapi. I required so many time that if there is somehow i can change or modify the auto created API according to my requirement. Like if i add one flag, if that flag value is true than i call one of my method and than append the result of my method with the result we are going to send to the client. Is this functionality currently exists or not and if exists than would appreciate if you please let me know.

Thanks

Linking Models are saved in the same model as array (they should be saved in different collection) so what if maximum size of document exceed i.e 16 MB?

Hi JKHeadley, I am just wondering to know that you create linking models for many to many relationship . And the relationship stores as an array on the same model, so what i am thinking because so many relationship would be there so that document size become heavy. So that will create issue after some time because maximum size of an document we have in Mongo is of 16 MB.

According to me there should be separate collection for the linking models.

So i just want to know your view on this means you are working on it or you see this differently, or i am wrong here please correct me.

Thanks

How can associate with multiple model?

Hi, @JKHeadley
I need to make association with multiple field, so is there any way to define association with more than one model?.
example:
my schema is like this:
masterField: [{

         abc: [{
             facility: {
                 type: Types.ObjectId,
                 ref: "abc"
             }
         }],
         xyz: [{
             item: {
                 type: Types.ObjectId,
                 ref: "xyz"
             }
     }]

}]

associations: {
type:.............?
model:...........?

}

How can i associate abc and xyz model with masterField so that i can embed masterField to populate abc and xyz ?

$sort with array

How can I sort the results with a array length ?

My collection have an 'likes' field that is an array of user ids, and I want to return the documents sorted with 'likes' length.

Can someone help me? #

Support a collection in the modelPath config property

The configuration have a property to customize the models route:

config.modelPath = 'models';

This is a single path directory so all the models must be inside.
It would be great if I could set up a collection of files instead of a single directory

For example, I have the next project tree:

myProject/
  |- index.js
  |- server.js
  |- config/
  |- modules/
      |- users_module/
          |- handlers/
          |- models/
              |- user.model.js
      |- article_module/
          |- handlers/
          |- models/
              |- article.model.js

And my config would be:

config.modelPath = ['modules/users_module/models/user.model', 'modules/article_module/models/article.model']';

This feature can be very useful to support a large projects with modular directory structure, like the above example.

Defining Schema

If there is a field in schema like this:

name: {
firstName: {
type: Types.String,
required: true
},
lastName: {
type: Types.String,
required: true
}
}

when i am going to save, it says : "message": ""value" at position 0 fails because ["name" is not allowed]
So how can save it on above schema?

Where to find documentation for older version

Hi JKHeadly,

I am just wondering to know where can i find the documentation for previous version of Rest-Hapi, like for example you changed param in Post and Pre of Create middle-ware , but what if somebody used older version as you updated the documentation so where i can find the older documentation for Middle-ware like i want to check the param which were send in say 0.23.2 version.
In the changelog.md you define what you changed but documentation wasn't there. So please help me in this concern because as i updated my rest-hapi version most of the things are not working properly.
Thanks

No gulpfile found

I tried to use your demo repo and tried to seed my model using ./node_modules/.bin/rest-hapi-cli seed or rest-hapi-cli seed for global, but it keeps on saying No gulpfile found even if I already have a gulpfile.js in the directory.

/register endpoint returning 504 Gateway timeout

Hi, I'm using your framework for some testing, and I can't guess what happens with the /register endpoint:

When I give this payload to the body:

{
  "user": {
    "firstName": "Test",
    "lastName": "Tester",
    "email": "[email protected]",
    "role": "Admin",
    "password": "testtest"
  },
  "registerType": "Register"
}

The server always returns:

{
"msec":228.90566400438547,"error":"An error occurred GenerateKey.","data":{"isBoom":true,"isServer":true,"output":
{"statusCode":504,"payload":{"statusCode":504,"error":"Gateway Timeout","message":"An error occurred."},"he
aders":{}}}}

Keep the good work btw!
Thanks

support "duplicate" field property

Any associated models referencing that model will duplicate those fields along with the reference _Id. This could allow for a shallow embed that will return a list of reference ids with their "duplicate" values, and a full embed that will return the fully embedded references

Policies & extraEndpoints

Hello,
Is it possible to re-use the policies also for endpoints done as extraEndpoints ?
Thanks
Jb

Error: TypeError: Joi.objectId is not a function

after seed already. then create api.js file and running.

TypeError: Joi.objectId is not a function at Schema.statics.routeOptions.extraEndpoints (/private/var/www/hapi-rest/models/user.model.js:107:28) at Object.generateRoutes (/private/var/www/hapi-rest/node_modules/rest-hapi/utilities/rest-helper-factory.js:93:13) at /private/var/www/hapi-rest/node_modules/rest-hapi/rest-hapi.js:92:36 at process.nextTick (/private/var/www/hapi-rest/node_modules/hapi/node_modules/hoek/lib/index.js:854:22) at _combinedTickCallback (internal/process/next_tick.js:73:7) at process._tickCallback (internal/process/next_tick.js:104:9)

Pre, Post (middle-ware) for update association API should be there

Hi,
i am working on some functionality where i require some post operation after the API created for association that internally call addOne method , but as i see there is middle-ware operation are only available for normal create , update but not for API created for association. So if someone need to do some work after the API like you provided post (middle-ware) how one can do the same in case of association API. Or i am wrong please correct me.

Thanks

add functionality of Upsert

Hi,
Sometime we want to update the document if that is already inserted otherwise we will insert a new one for this like mongo give us Upsert:true option, so suppose i am using Rest-Hapi then how can i achieve the same thing via Rest-Hapi, i mean is there a way to do this.

Thanks

How to get the validateFunc returned data in pre hook of internal API made by Rest-Hapi.

Hi, I am just wondering to know that,

How can we add some extra info in PAYLOAD object in auth (validateFunc) function so that we can use that in pre (create) hook in internal API (generated by Rest-Hapi). Because as i want some user info for some validation in my pre hook, like:-

Schema.statics = {
		collectionName: modelName,
		routeOptions: {
			scope:{
				createScope:"Occupant"
			},
create: {
        pre : function(payload, Log){
        	console.log(payload);	// here i get only payload sent from client side but i want some other info that returned from the validateFunc of "hapi-auth-jwt2"
        }
}
}

but as i only able to get the payload there so how can i get the additional info as well.
You can get the detail question i posted over stackoverflow:-
https://stackoverflow.com/questions/44546596/how-to-get-result-of-validatefunc-in-pre-of-auto-created-api-rest-hapi
Please help me regarding this ASAP. Thanks

Engine restrictions

I'm using yarn as package manager and sometimes I get some warnings about the engine being not compatible. It's currently fixed as 6.0.0. I've just run the tests over v6.8.0 and all tests are green. Do you really have this restriction for some reason?

{
  "name": "rest-hapi",
  "version": "0.15.1",
  "description": "A RESTful API generator for hapi",
  "main": "rest-hapi.js",
  "bin": {
    "rest-hapi-cli": "./rest-hapi-cli.js"
  },
  "engines": {
    "node": "6.0.0",
    "npm": "4.0.5"
  },
  ...

TypeError: Cannot read property 'schemaName' of undefined

Hi there. I keep running into this error when trying to startup my application. I've looked for help in Google, with no luck. Unfortunately i can't share much of the code, but here's the stacktrace:

[18:18:32.087] 47383 NOTE     api/layout/List β€” Generating List endpoint for layout
[18:18:32.093] 47383 ERROR    node_modules/rest-hapi/utilities/rest-helper-factory.js:98:16 api β€” Error: TypeError: Cannot read property 'schemaName' of undefined
[18:18:32.093] 47383 ERROR    node_modules/rest-hapi/utilities/rest-helper-factory.js:98:16 api β€”     at Object.generateJoiModelFromFieldType (/var/www/private/node_modules/rest-hapi/utilities/joi-mongoose-helper.js:213:27)
[18:18:32.093] 47383 ERROR    node_modules/rest-hapi/utilities/rest-helper-factory.js:98:16 api β€”     at /var/www/private/node_modules/rest-hapi/utilities/rest-helper-factory.js:169:46
[18:18:32.093] 47383 ERROR    node_modules/rest-hapi/utilities/rest-helper-factory.js:98:16 api β€”     at arrayEach (/var/www/private/node_modules/rest-hapi/node_modules/lodash/index.js:1289:13)
[18:18:32.093] 47383 ERROR    node_modules/rest-hapi/utilities/rest-helper-factory.js:98:16 api β€”     at Function.<anonymous> (/var/www/private/node_modules/rest-hapi/node_modules/lodash/index.js:3345:13)
[18:18:32.093] 47383 ERROR    node_modules/rest-hapi/utilities/rest-helper-factory.js:98:16 api β€”     at Object.generateListEndpoint (/var/www/private/node_modules/rest-hapi/utilities/rest-helper-factory.js:168:11)
[18:18:32.093] 47383 ERROR    node_modules/rest-hapi/utilities/rest-helper-factory.js:98:16 api β€”     at Object.generateRoutes (/var/www/private/node_modules/rest-hapi/utilities/rest-helper-factory.js:51:16)
[18:18:32.093] 47383 ERROR    node_modules/rest-hapi/utilities/rest-helper-factory.js:98:16 api β€”     at /var/www/private/node_modules/rest-hapi/rest-hapi.js:92:36
[18:18:32.093] 47383 ERROR    node_modules/rest-hapi/utilities/rest-helper-factory.js:98:16 api β€”     at process.nextTick (/var/www/private/node_modules/hapi/node_modules/hoek/lib/index.js:858:22)
[18:18:32.093] 47383 ERROR    node_modules/rest-hapi/utilities/rest-helper-factory.js:98:16 api β€”     at _combinedTickCallback (internal/process/next_tick.js:73:7)
[18:18:32.093] 47383 ERROR    node_modules/rest-hapi/utilities/rest-helper-factory.js:98:16 api β€”     at process._tickCallback (internal/process/next_tick.js:104:9)

Tell me if you need more details.
I'm using the latest version of rest-hapi.
Thanks.

can we use $embed for array of array field?

@JKHeadley would like to use $embed for getting inner array field data.
my schema is like this...
facilitiesPerFloor: [{
suiteInfo: {
floorNo: {
type: Types.Number
}
},
facilities: [{
type: Types.ObjectId,
ref: "facility"
}]
}]

Holding Data
"facilitiesPerFloor": [
{
"_id": "5996d930daec05116aed9e35",
"facilities": [
"5996d83a0c2b83113cdfd40c",
"5996d83a0c2b83113cdfd41c"
],
"suiteInfo": {
"floorNo": 1
}
}
]

Note: facilitiesPerFloor contains facilities array where multiple facility can be. Now how i can use $embed for getting/populating second level of facilities data.

Thanks.

Association not updated automatically need to call separate API for update in associated models

Hi,
I am using Rest-Hapi and it provides functionality to create auto API for association. But just wondering to know why it not update the associated model with the single call. We need to call the separate API for updating associated model.
For example:-
Suppose i have may to many association between FirstResponder and Occupants , so as Occupant call the API for assigning the FR , so i need FR _id into Occupant and Occupant _id into FR, but for that i need to call to separate API from front-end, first that update FR _id into occupant and after the response (then block ) of that API i called another API that update Occupant _id into FR (FirstResponder). So if i am not wrong means if both have many to many association than automatically the association handling should be there means i just made one call and to whom the model is associated auto updated with the other model _Id.

Any explanation is much appreciated on this.

Thanks

First time setup/Demo error

I am trying to start up a basic rest-hapi example using your example code, but I am encountering an error. When I launch ./node_modules/.bin/rest-hapi-cli seed I get this error:

[21:10:20] Working directory changed to ~/WebstormProjects/deleteme/node_modules/rest-hapi

module.js:471
    throw err;
    ^

Error: Cannot find module '../tests/test-helper.js'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/kpfromer/WebstormProjects/deleteme/node_modules/rest-hapi/gulp/test.js:6:20)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at requireDir (/Users/kpfromer/WebstormProjects/deleteme/node_modules/require-dir/index.js:123:33)
    at Object.<anonymous> (/Users/kpfromer/WebstormProjects/deleteme/node_modules/rest-hapi/gulpfile.js:9:23)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)

Authorization input box is not showing in rest-hapi API swagger UI

hapi1

Context

my package.json is look like

"rest-hapi": "0.23.2",
 "hapi": "^15.2.0",
"hapi-auth-bearer-token": "^3.1.1",
"hapi-auth-jwt2": "^7.2.4",
"hapi-passport": "0.0.6",
"hapi-swagger": "^2.2.4",
  • hapi-swgger version: "hapi-swagger": "^2.2.4",

all the api is creating automatically..so i don`t have any idea how can set Authorization in every api which is created automatically

i am using "rest-hapi": "0.23.2"

please give me solution

Allow, flexible object fields for models.

I have a requirement, where I want to allow the users of my service to input any data into my model. Some metadata.

I have tried using Types.Mixed and Types.Object to get past this, but when I make a request, rest-hapi says key is not allowed.
I think this was working uptil v 0.20, I recently updated to 0.33.

Thanks in advance.

$where does not support real raw queries

Hello,
For $where field when provided simple selection like e.g. {"doc_nr": "1005"} works perfectly fine. For more complex including special operators (with $) it does not work, e.g.: { "doc_nr": {$ne: "1005"}}

result:

ERROR node_modules/rest-hapi/utilities/error-helper.js:27:11 api/docs/List β€” error: SyntaxError: Unexpected token $ in JSON at position 17

Thanks
JB

when i used config database have connect 2 time

before register plugin used

restHapi.config.mongo.URL = 'mongodb://localhost/test_api';

this is result

[11:20:18.085] 82949 LOG      api/mongoose β€” Connecting to Database...:
[11:20:18.091] 82949 LOG      api/mongoose β€” 	URI: `mongodb://localhost/rest_hapi`
[11:20:18.092] 82949 LOG      api/mongoose β€” 	URL: `mongodb://localhost/test_api`
[11:20:18.101] 82949 LOG      api β€” Initializing Server...
...

images

Using this issue to store images since npm doesn't like them in the repo.

Proposal: updateHandler to use findById() + findOneAndUpdate()

Using the recent changes/additions to the middleware, I've been able to have my create, list and find endpoints use the authenticated user's credentials. For example:

      create: {
        pre: function(payload, request, Log) {
          payload.account = request.auth.credentials.account;
          return Promise.resolve(payload);
        },
      },
      list: {
        pre: function(query, request, Log) {
          query.account = request.auth.credentials.account;
          return Promise.resolve(query);
        },
      },

Now I'm working on adding the same functionality to the update endpoint. Currently the update handler simply calls model.findByIdAndUpdate(_id, payload). I propose changing this to:

mongooseQuery = model.findById(_id);
mongooseQuery = QueryHelper.createMongooseQuery(model, query, mongooseQuery, Log);
mongooseQuery.findOneAndUpdate(payload)

This way, the document specified by _id will only be found and updated if it also matches any additional constraints in the query.


I have a proof-of-concept implementation at https://github.com/pangeamedia/rest-hapi/commit/fea600d713dce4f59b92bcb2ac7637399039b017#diff-cae92e718d9d94bbd9debab4fbf43095L734
I've tested this POC in my app, and it works as expected.

The main difficulty is that the update.pre middleware function currently only returns the payload, but I need it to return the query. For the proof-of-concept, I have update.pre return the query as payload.$query. This is not ideal, but it maintains backwards compatibility.

Other ideas I had include update.pre returning an object like { payload: payload, query: query } or an array like [ payload, query ], possibly maintaining backwards compatibility in either case by having the update handler introspect the returned value. I don't know what approach is best.

Thoughts?

question: dynamic fields in model

Hi,
I'd like to put some dynamic attributes to the model and I was thinking to use:

attributes : [new mongoose.Schema({ Name: {type: String}, Value : {type: String} }, {strict: false}) ]

or even

attributes : [mongoose.Schema.Types.Mixed]

Is this something which is not recommended?

Thanks
JB

Support scope/permissions for individual model properties.

Example:

'use strict';

module.exports = function (mongoose) {
    const modelName = "user";
    const Types = mongoose.Schema.Types;
    const Schema = new mongoose.Schema({
        isActive: {
            type: Types.Boolean,
            default: false
            scope: {
                updateScope: ['Admin']              //<------only users with 'Admin' scope can update this property 
            },
            allowOnCreate: false
        },
        email: {
            type: Types.String,
            unique: true,
            index: true,
            sparse: true
        },
        password: {
            type: Types.String,
            exclude: true,
            allowOnUpdate: false
        }
    }, {collection: modelName});

    Schema.statics = {
        collectionName: modelName,
        routeOptions: {
            associations: {
            }
        }
    };

    return Schema;
};

Converting circular structure to JSON

Hello everybody.

I'm trying to duplicate my actual production environment to create dev environment in same server.
I already duplicate database and nginx configuration for another domain, but, when I access my dev environment I got the following error:

Debug: internal, implementation, error TypeError: Uncaught error: Converting circular structure to JSON at Object.stringify (native) at Object.internals.paths.build.internals.paths.buildRoutes.internals.hasFileType (/var/www/dev-api.mydomain.com.br/public/node_modules/hapi-swagger/lib/paths.js:381:28) at /var/www/dev-api.mydomain.com.br/public/node_modules/hapi-swagger/lib/paths.js:223:23 at Array.forEach (native) at internals.paths.build.internals.paths.buildRoutes.routes [as buildRoutes] (/var/www/dev-api.mydomain.com.br/public/node_modules/hapi-swagger/lib/paths.js:179:12) at internals.paths.build.routes.forEach [as build] (/var/www/dev-api.mydomain.com.br/public/node_modules/hapi-swagger/lib/paths.js:151:17) at Object.builder.getSwaggerJSON (/var/www/dev-api.mydomain.com.br/public/node_modules/hapi-swagger/lib/builder.js:110:26) at settings.log.plugin.route.config.handler.plugin.methods.getSwaggerJSON.Builder.getSwaggerJSON (/var/www/dev-api.mydomain.com.br/public/node_modules/hapi-swagger/lib/index.js:115:29) at Object.exports.execute.internals.prerequisites.internals.handler.finalize [as handler] (/var/www/dev-api.mydomain.com.br/public/node_modules/hapi/lib/handler.js:101:51) at /var/www/dev-api.mydomain.com.br/public/node_modules/hapi/lib/handler.js:32:23 at internals.Protect.run.finish [as run] (/var/www/dev-api.mydomain.com.br/public/node_modules/hapi/lib/protect.js:60:12) at exports.execute.finalize (/var/www/dev-api.mydomain.com.br/public/node_modules/hapi/lib/handler.js:26:22) at each (/var/www/dev-api.mydomain.com.br/public/node_modules/hapi/lib/request.js:401:16) at iterate (/var/www/dev-api.mydomain.com.br/public/node_modules/items/lib/index.js:36:13) at done (/var/www/dev-api.mydomain.com.br/public/node_modules/items/lib/index.js:28:25) at module.exports.internals.state.next (/var/www/dev-api.mydomain.com.br/public/node_modules/hapi/lib/route.js:292:16)

My production environment is working.
Anyone can help-me with this?

(I have replaced the url of my domain to dev-api.mydomain.com.br for obvious reasons)

Thanks :)

Handling duplicate entry error gracefully.

Hi, currently if there is an attempt of duplicate entry on unique keys, the system sends a 500 status with an Internal server error.
I'm thinking that we should handle this as a special case, coz in most cases the users of application would like to know that duplicate data is being inserted.

I suggest we should send a 409 Conflict with a duplicate content message.
Would like to hear your thoughts on this.

add option for separate linking model collection

Add an option to allow linking models to exist within their own collection. This would prevent parent model documents from growing too large when there are many related (many-to-many) documents. This option will most likely exist both as a global setting and as a property within the association object/definition.

use $or on restHapi List

When i try to make a list using restHapy i recive this error:

MongoError: $or must be an array

restHapi.list(model, {"$or" : [{name:"ases"},{framework:"asease"}]},Log).then(function (result) {

type: [Types.ObjectId] causes error

Given a model:

    var modelName = "share";
    var Types = mongoose.Schema.Types;
    var Schema = new mongoose.Schema({
        caption: {
            type: Types.String
        },
        hashTags: {
            type: [Types.ObjectId],
            ref: "hashtag",
        }
    }, { collection: modelName });

and a POST payload:

{
    caption: "Some caption",
    hashTags: ["597819a083f229000111e502","597786af85976b0001c973d3"]
}

an error will occur:
Error: β€œvalue” must be an array. child β€œhashTags” fails because [β€œhashTags” at position 0 fails because [β€œ0" must be a string]]

Need to look into this, but the current fix is to update the hashTags to type [Types.String]:

    var modelName = "share";
    var Types = mongoose.Schema.Types;
    var Schema = new mongoose.Schema({
        caption: {
            type: Types.String
        },
        hashTags: {
            type: [Types.String],
            ref: "hashtag",
        }
    }, { collection: modelName });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.