Adding array of objects to mongodb issue - node.js
I'm having issues adding an array of objects to mongodb. The problem is related to when I get the posts ngOnInit() and there is an entry for _id like this before I start adding anything to inviteGroup
If I add this.inviteGroup = [] to get rid of _id first entry, then I can successfully add to the database my invite like in this image. Is there a way to not have that _id that's related to my mongoose schema?
but naturally the this.inviteGroup = [] makes it so I can have only one entry at a time since it erases everything on page load. How can I make that _id entry not there anymore so that when I do a .push() it doesn't cause a page reload because it throws off the .push(). I want to have multiple entries in db for each invite. Is it my mongoose model that's the issue? I appreciate any help!
mongoose schema definition
inviteGroup: {
bidderId: { type: String, lowercase: true, trim: true },
username: { type: String, lowercase: true, trim: true }
}
app.js
app.patch("/api/listings/:id", (req, res) => {
console.log("INVITE GRdddOUP IS");
console.log(req.body);
console.log(req.body[0].biddingUserId);
let invites;
if (req.body[0].biddingUserId) {
invites = req.body;
console.log("INVITE IS");
}
console.log(invites);
if (invites) {
console.log("INVITE GROUP IS");
console.log(req.params.id);
Post.findByIdAndUpdate(
{ _id: req.params.id },
{
inviteGroup: invites
},
function(err, docs) {
if (err) {
console.log(err);
res.json(err);
} else {
return true;
console.log(docs);
}
}
);
component.ts
import {
Component,
OnInit,
ViewChild,
OnDestroy,
AfterViewInit
} from "#angular/core";
import { Router } from "#angular/router";
import {
MatTableDataSource,
MatPaginator,
MatSort,
MatDialog
} from "#angular/material";
import { NgForm, FormControl } from "#angular/forms";
import { SubmitListingService } from "../submit-listing/submit-auction.service";
import { BidderInvite } from "./bidder-invite.model";
import { Observable, Subject } from "rxjs";
import { startWith, map, takeUntil } from "rxjs/operators";
import { Page } from "ngx-pagination/dist/pagination-controls.directive";
import { BidderInviteRetrieved } from "./bidder-invite-retrieved";
#Component({
selector: "app-private-auction-invite",
templateUrl: "./private-auction-invite.component.html",
styleUrls: ["./private-auction-invite.component.css"]
})
export class PrivateAuctionInviteComponent
implements OnInit, AfterViewInit, OnDestroy {
allMyPeopleAreInvited: boolean;
auctionId: string;
dataSource: MatTableDataSource<any> = new MatTableDataSource();
timeout: any = null;
posts: BidderInviteRetrieved[];
artistId: string;
bidderId: string;
inviteGroup: BidderInvite[] = [];
test: any[] = [];
value: string;
usernameFound: string;
userSearched: string;
invites: BidderInvite[] = [];
destroy = new Subject();
inviteName: string;
filteredOptions: Observable<string[]>;
myControl = new FormControl();
selectedValue: string;
url: string;
displayedColumnsInvites: string[] = ["User", "revokeInvite"];
options: string[] = [];
#ViewChild(MatSort, { static: false }) set sort(sort: MatSort) {
this.dataSource.sort = sort;
}
#ViewChild(MatPaginator, { static: false }) set paginator(
paginator: MatPaginator
) {
this.dataSource.paginator = paginator;
}
constructor(
private router: Router,
private submitListingService: SubmitListingService
) {}
ngOnInit() {
this.inviteGroup = [];
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
this.allMyPeopleAreInvited = false;
this.url = this.router.url;
const value = this.router.url.split("/");
this.auctionId = value[2];
this.artistId = value[3];
this.submitListingService
.getPrivateAuctionInviteList(this.auctionId)
.pipe(takeUntil(this.destroy))
.subscribe(res => {
this.inviteGroup = res.posts;
console.log("res");
console.log(res);
console.log(this.inviteGroup);
if (this.inviteGroup["_id"].length > 2) {
this.inviteGroup = [];
console.log(this.inviteGroup);
}
});
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(""),
map(value => this._filter(value))
);
}
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
this.dataSource = new MatTableDataSource(this.inviteGroup);
this.dataSource.data = this.inviteGroup;
}
sendInvite(form: NgForm) {
if (form.invalid) {
return;
}
let counter: number;
counter = 0;
console.log("USER " + this.value);
console.log("POST LEGNTH: " + this.posts.length);
for (let i = 0; i < this.posts.length; i++) {
counter = counter++;
console.log("post");
console.log(form.value.username);
let user = this.posts[i].username.trim().toLowerCase();
let enteredUser = form.value.username.trim().toLowerCase();
console.log("COUNTER LOOP NUMBER: " + counter);
if (enteredUser === user) {
this.bidderId = this.posts[i].id;
console.log(this.inviteGroup);
let invites = this.inviteGroup;
console.log("INVITE LENGTH = " + this.inviteGroup.length);
console.log(invites.indexOf);
this.inviteGroup.push({
biddingUserId: this.bidderId,
username: this.posts[i].username
});
console.log(this.inviteGroup);
console.log("invite group");
console.log(this.inviteGroup);
//this.posts = [];
this.dataSource.data = this.inviteGroup;
console.log("invite group");
}
}
console.log("BIDDER ID " + this.bidderId);
if (this.bidderId === null || this.bidderId === undefined) {
console.log("SOMETHING WENT WRONG");
}
console.log("made it to next section");
let invites = this.inviteGroup;
console.log("invites[0].username");
console.log("filtering....");
invites = invites.filter((obj, pos, arr) => {
return (
arr.map(mapObj => mapObj["bidderId"]).indexOf(obj["bidderId"]) === pos
);
});
console.log("invites");
console.log(invites);
this.submitListingService
.sendPrivateAuctionInvite(this.auctionId, invites)
.pipe(takeUntil(this.destroy))
.subscribe(res => {
console.log("res");
console.log(res);
});
}
private onKeySearch(event: any) {
console.log("EVENT IS ");
console.log(event);
clearTimeout(this.timeout);
var $this = this;
this.timeout = setTimeout(function() {
if (event.keyCode !== 13) {
$this.executeListing(event.target.value);
}
}, 1000);
}
private executeListing(bidderName: string) {
console.log("BIDDERNAME");
console.log(bidderName);
if (bidderName === "[Object object]") {
return;
}
if (bidderName.length < 4) {
return;
}
if (bidderName.length > 3) {
this.submitListingService
.getUserIdAutoComplete(bidderName)
.pipe(takeUntil(this.destroy))
.subscribe(res => {
console.log("res");
console.log(res);
this.posts = res.posts;
console.log(this.posts);
// this.artists = res.posts;
});
}
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter(
option => option.toLowerCase().indexOf(filterValue) === 0
);
console.log("OPTION IS " + filterValue);
}
storeUserPrivaeAuctionInvite(user: Page) {
console.log("USER VALUE I S" + user);
}
ngOnDestroy() {
this.destroy.next();
this.destroy.complete();
}
}
angular service
sendPrivateAuctionInvite(id: string, inviteGroup1: BidderInvite[]) {
// console.log(inviteGroup1);
return this.http.patch(
`http://localhost:3000/api/listings/${id}/`,
inviteGroup1
);
}
BidderInvite model
export interface BidderInvite {
biddingUserId: string;
username: string;
}
Is your schema definition supposed to be:
inviteGroup: {
type: [inviteSchema]
default: undefined //if you want to unset []
}
invite: {
bidderId: { type: String, lowercase: true, trim: true },
username: { type: String, lowercase: true, trim: true }
}
(See https://mongoosejs.com/docs/schematypes.html#arrays)
Try caching to prevent a reload. (See https://github.com/isaacs/node-lru-cache) and How to stop MongoDB from reloading data every time I refresh a page?
Try projection to exclude _id in a query output with _id: 0. See https://docs.mongodb.com/v3.2/tutorial/project-fields-from-query-results/#return-all-but-the-excluded-field
Try this. Hope it will help you.
Post.findByIdAndUpdate(
{ _id: req.params.id },
{
inviteGroup: invites
},
{select: {_id: 0}}, // sets the document fields to return
function(err, docs) {
if (err) {
console.log(err);
res.json(err);
} else {
return true;
console.log(docs);
}
}
);
If I understood your question right, the problem is related to the lack of operator at the update method.
When you use something like:
Post.findByIdAndUpdate(
{ _id: req.params.id },
{
inviteGroup: invites // <-- Update statement
},
function(err, docs) {
//...
}
);
It will replace the full value of the inviteGroup field.
In order to add an item to an existent array on the database, you will need to use $push or $addToSet operator, along with $each operator.
The $push and $addToSet operators, only add/append one item per time, so the use of $each is necessary to interact with every item present on the invites array. In the following examples, I will include that because I believe is what you will need. But please, take the time to read the linked documentation of every operator so you can find more samples.
The $push operator appends a specified value to an array, making no extra verification if the value that is been added already exists on the field or not. As:
//document on mongodb, before the update
// { _id : "1", inviteGroup : [] }
//Invites from the request
// invites = [ { bidderId:"5e2350c7f88cfb331c4f67de", username:"artist1"} ];
//update method
Post.findByIdAndUpdate(
{ _id: req.params.id }, //req.params.id = "1"
{ $push : { inviteGroup: { $each : invites } } },
function(err, docs) {
//...
}
);
//document on mongodb, after the update
/*
{
_id : "1",
inviteGroup : [ { bidderId:"5e2350c7f88cfb331c4f67de", username:"artist1"} ]
}
*/
If you call the update method again with the same values:
Post.findByIdAndUpdate(
{ _id: req.params.id }, //req.params.id = "1"
{ $push : { inviteGroup: { $each : invites } } },
function(err, docs) { }
);
// the end document will be like:
/*
{
_id : "1",
inviteGroup : [
{ bidderId:"5e2350c7f88cfb331c4f67de", username:"artist1"},
{ bidderId:"5e2350c7f88cfb331c4f67de", username:"artist1"}
]
}
*/
In the same way, the $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array. Like:
//document on mongodb, before the update
// { _id : "1", inviteGroup : [] }
//Invites from the request
// invites = [ { bidderId:"5e2350c7f88cfb331c4f67de", username:"artist1"} ];
//update method
Post.findByIdAndUpdate(
{ _id: req.params.id }, //req.params.id = "1"
{ $addToSet : { inviteGroup: { $each : invites } } },
function(err, docs) {
//...
}
);
//document on mongodb, after the update
/*
{
_id : "1",
inviteGroup : [ { bidderId:"5e2350c7f88cfb331c4f67de", username:"artist1"} ]
}
*/
If you call the update method again with the same values:
Post.findByIdAndUpdate(
{ _id: req.params.id }, //req.params.id = "1"
{ $addToSet : { inviteGroup: { $each : invites } } },
function(err, docs) { }
);
//the end document will be the same because the same value was already on the list:
/*
{
_id : "1",
inviteGroup : [ { bidderId:"5e2350c7f88cfb331c4f67de", username:"artist1"} ]
}
*/
Well, I hope that was what you looking for. =]
Related
Mongoose / Node : How to add an object to an array?
I have a problem when I try to update an array with Mongoose/Node. I want to add my new price for example, req.body value is : { price: 12 } or req.body is : { description: 'my description' } but when I do this the total array is replace by just my new object ! :/ Here is my model: const restaurantSchema = mongoose.Schema({ userId: { type: Object, required: true }, name: { type: String }, menus: [{ name: { type: String }, price: { type: String }, description: { type: String }, }], }) And my node Js code : const menuUpdate = req.body; const menuId = req.params.menuId; const userId = userIdFromToken(req); const filter = { userId: userId, "menus._id": menuId }; const update = { $set: { "menus.$": menuUpdate } }; const options = { upsert: true, new: true }; Restaurant.findOneAndUpdate(filter, update, options).then(() => { return res.status(204).json({ message: "Menus updated " }); }); Thanks for your help, David ==== I change my code with the help of #aks, like this... const menuUpdate = req.body; for (const [key, value] of Object.entries(menuUpdate)) { this.menuKey = `${key}`; this.menuValue = `${value}`; } if (this.menuKey === 'name') { this.update = { $set: { "menus.$.name": this.menuValue } }; } if (this.menuKey === 'price') { this.update = { $set: { "menus.$.price": this.menuValue } }; } if (this.menuKey === 'description') { this.update = { $set: { "menus.$.description": this.menuValue } }; } const menuId = req.params.menuId; const userId = userIdFromToken(req); const filter = { userId: userId, 'menus._id': menuId, }; const options = { upsert: true, new: true }; Restaurant .findOneAndUpdate( filter, this.update, options, ) .then ( () => { return res.status(204).json({ message: 'Menus updated ' }); }); Is there a way to simplify that without if ?
Your Node code menus: [{ name: "toto", price: 25, description: "custom sweet", }] Now You have to update only the price from 25 to 45 for that you have to send the whole array. So you have to simple set the array with this value And if you go to other approach then on req.body add one more parameter i.e menuIndex: 2 And on you update request make the condition if menuIndex is 2 then update specific column const menuUpdate = req.body; const menuId = req.params.menuId; const userId = userIdFromToken(req); const filter = { userId: userId, "menus._id": menuId }; let update = {}; if (req.body.menuIndex === 1) { update = { $set: { "menus.$.name": req,body.val} }; } if (req.body.menuIndex === 2) { update = { $set: { "menus.$.price": req,body.val } }; } if (req.body.menuIndex === 3) { update = { $set: { "menus.$.description": req,body.val} }; } const options = { upsert: true, new: true }; Restaurant.findOneAndUpdate(filter, update, options).then(() => { return res.status(204).json({ message: "Menus updated " }); });
Mongoose, MATCH operator doesn't return results
The company parameter has a valid value to obtain the result, but I get an empty array. company = company.replace('.', ''); company = company.replace('.', ''); company = company.replace('-', ''); company = company.replace('/', ''); try { const result = await cteModel.aggregate([ { $addFields': { date': { $dateFromString': { 'dateString': '$dataEmissao' } } } }, { $match: { 'empresa': company } }, { $sort: { date: -1, _id: 1 } }]); res.status(200).send(result); } catch (error) { console.log(error); return res.status(500).json(error); }
The query return the deisered result if I substitute the variable by string, like this : { $match: { 'empresa': '1111' } },
how to update an object of an element in array in mongodb?
This is the structure i have, i want to update the nested array element if an object key matches for example - i want to match grnno :"10431000" and update the other keys of that object like vehicle_no,invoice_no etc. { "_id" : ObjectId("5f128b8aeb27bb63057e3887"), "requirements" : [ { "grns" : [ { "invoice_no" : "123", "vehicle_no" : "345", "req_id" : "5f128c6deb27bb63057e388a", "grnno" : "10431000" }, { "invoice_no" : "abc", "vehicle_no" : "def", "req_id" : "5f128c6deb27bb63057e388a", "grnno" : "10431001" } ] } ] } I have tried this code db.po_grn.update({ "requirements.grns.grnno":"10431001" }, { $set: { "requirements.$.grns": {"invoice_no":"test",vehicle_no:"5455"} } }) But this is changing the structure i have like this "requirements" : [ { "grns" : { "invoice_no" : "test", "vehicle_no":"5455" }, "req_id" : ObjectId("5f128b8aeb27bb63057e3886") } ], grns key should be array, and update should be of the particular object which matches the key "grnno". Please help me out. Thanks. ==Edit== var grnno = req.body.grnno; db.po_grn.find({ "requirements.grns.grnno":grnno }).toArray(function(err, po_grn) { console.log("po_grn",po_grn); if (po_grn.length > 0) { console.log("data.grn.grnno ", grnno); var query = { requirements: { $elemMatch: { "grns.grnno": grnno } } }; var update = { $set: { 'requirements.$[].grns.$[inner].invoice_no': data.invoice_no, 'requirements.$[].grns.$[inner].vehicle_no': data.vehicle_no, } }; var options = { arrayFilters: [ { "inner.grnno" : grnno } ] }; db.po_grn.update(query, update, options , function(er, grn) { console.log("grn",grn,"er",er) res.send({ status: 1, message: "Grn updated successfully" }); } ); } else { res.send({ status: 0, message: "Grn not found " }); } })
Use a combination of $[] positional-all operator with array filters to update your inner nested document. var query = { requirements: { $elemMatch: { "grns.grnno": "10431001" } } }; var update = { $set: { 'requirements.$[].grns.$[inner].invoice_no': "test", 'requirements.$[].grns.$[inner].vehicle_no': "5455", } }; var options = { arrayFilters: [ { "inner.grnno" : "10431001" } ] }; db.collection.update(query, update, options); Update - NodeJS native MongoDb driver code attached, which is working fine const { MongoClient } = require('mongodb'); const url = "mongodb://localhost:27017/"; MongoClient.connect(url, function(err, db) { if (err) { throw err; } const dbo = db.db("test"); (async() => { const query = { requirements: { $elemMatch: { "grns.grnno": "10431001" } } }; const update = { $set: { 'requirements.$[].grns.$[inner].invoice_no': "test", 'requirements.$[].grns.$[inner].vehicle_no': "5455", } }; const options = { arrayFilters: [ { "inner.grnno" : "10431001" } ], multi: true }; try { const updateResult = await dbo.collection("collection").update(query, update, options); } catch (err) { console.error(err); } db.close(); })(); });
mongoDB find, update and pull in One Query
I want to do all the find the data from the collection and then want to update some field as well as depending on want to empty the array. const addCityFilter = (req, res) => { if (req.body.aCities === "") { res.status(409).jsonp({ message: adminMessages.err_fill_val_properly }); return false; } else { var Cities = req.body.aCities.split(","); // It will make array of Cities const filterType = { "geoGraphicalFilter.filterType": "cities", "geoGraphicalFilter.countries": [], "geoGraphicalFilter.aCoordinates": [] }; /** While using $addToset it ensure that to not add Duplicate Value * $each will add all values in array */ huntingModel .update( { _id: req.body.id, }, { $addToSet: { "geoGraphicalFilter.cities": { $each: Cities } } }, {$set:{filterType}}, ).then(function(data) { res.status(200).jsonp({ message: adminMessages.succ_cityFilter_added }); }); } }; Collection geoGraphicalFilter: { filterType: { type:String, enum: ["countries", "cities", "polygons"], default: "countries" }, countries: { type: Array }, cities: { type: Array }, aCoordinates: [ { polygons: { type: Array } } ] } But as result, the only city array is getting an update. No changes in filterType.
You appear to be passing the $set of filterType as the options argument, not the update argument. huntingModel .update( { _id: req.body.id, }, { $addToSet: { "geoGraphicalFilter.cities": { $each: Cities } }, $set: { filterType } } ).then(function(data) { res.status(200).jsonp({ message: adminMessages.succ_cityFilter_added }); });
Abstract type Node must resolve to an Object type at runtime for field Root.node with value \"\",received \"null\"."
I am implementing a search feature with react and relay. Below is my schema.js var { nodeInterface, nodeField } = nodeDefinitions( (globalId) => { var { type, id } = fromGlobalId(globalId); if (type === 'User') { return getUser(id); }else if (type === 'Post') { return getPost(id); }else if (type === 'Setting') { return getSetting(id); } return null; }, (obj) => { if (obj instanceof User) { return userType; }else if (obj instanceof Post) { return postType; }else if (obj instanceof Setting) { return settingType; } return null; } ); var postType = new GraphQLObjectType({ name: 'Post', fields: { _id: { type: new GraphQLNonNull(GraphQLID) }, createdAt: { type: GraphQLString }, id: globalIdField('Post'), title: { type: GraphQLString }, color: { type: GraphQLString }, userId: globalIdField('User'), username: { type: GraphQLString, resolve: (post) => getUserById(post.userId), }, content: { type: GraphQLString }, images: { type: postImageType, description: "Post's main image links" } }, interfaces: [nodeInterface] }); const { connectionType: postConnection, } = connectionDefinitions({name: 'Post', nodeType: postType}); var settingType = new GraphQLObjectType({ name: 'Setting', fields: { _id: { type: new GraphQLNonNull(GraphQLID) }, id: globalIdField('Setting'), amount: { type: GraphQLString }, all_posts: { type: postConnection, args: { ...connectionArgs, query: {type: GraphQLString} }, resolve: (rootValue, args) => connectionFromPromisedArray( getAllPosts(rootValue, args), args ), }, }, interfaces: [nodeInterface] }); var Root = new GraphQLObjectType({ name: 'Root', fields: () => ({ node: nodeField, setting: { type: settingType, args: { ...connectionArgs, currency: {type: GraphQLString} }, resolve: (rootValue, args) => { return getSetting(args.currency).then(function(data){ return data[0]; }).then(null,function(err){ return err; }); } }, }) }); Below is my database.js export function getAllPosts(params,args) { let findTitle = {}; let findContent = {}; if (args.query) { findTitle.title = new RegExp(args.query, 'i'); findContent.content = new RegExp(args.query, 'i'); } console.log("getAllPosts",args) return new Promise((resolve, reject) => { Post.find({$or: [findTitle,findContent]}).sort({createdAt: 'descending'}).exec({}, function(err, posts) { if (err) { resolve({}) } else { resolve(posts) } }); }) } Now I want to fetch all posts by $query variable So in view I wrote like this import React, { Component } from 'react'; import Relay from 'react-relay'; class BlogList extends Component { constructor(props) { super(props); this.state = { query: '', }; this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(){ this.props.relay.setVariables({query: this.state.query}); } render() { return ( <div className="input-group col-md-12"> <input type="text" onChange={this.handleChange.bind(this,"query")} value={this.state.query} name="query" placeholder="Enter Title or content"/><br/> <span className="input-group-btn"> <button type="button" onClick={this.handleSubmit} className="btn btn-info btn-lg"> <i className="glyphicon glyphicon-search"></i> </button> </span> </div> ) } }; export default Relay.createContainer(BlogList, { initialVariables: { query: '' }, fragments: { viewer: () => Relay.QL` fragment on Setting { id, all_posts(first: 10000000,query: $query) { edges { node { id, _id, title, content, createdAt, username, color, images{ full } } } } } `, }, }); And in routes I have const SettingQueries = { viewer: () => Relay.QL`query{ setting(currency: "USD") }`, } export default [{ path: '/', component: App, queries: UserQueries,PostQueries,SettingQueries, indexRoute: { component: IndexBody, }, childRoutes: [ ,{ path: 'settings', component: Setting, queries: SettingQueries, }] }] Things are working on /graphql as but when I search from website it generates error in response { "data": { "node": null }, "errors": [ { "message": "Abstract type Node must resolve to an Object type at runtime for field Root.node with value \"\",received \"null\".", "locations": [ { "line": 2, "column": 3 } ] } ] } as my web-browser is sending requests as below Please suggest me what am I missing? Also If I need to add some additional information please let me know.
The problem might be in your nodeDefinitions() function. First callback, also named idFetcher must return a single object. However, i see in your definition that you return a collection var { nodeInterface, nodeField } = nodeDefinitions( (globalId) => { var { type, id } = fromGlobalId(globalId); ... }else if (type === 'Post') { return getPosts(); // this should be getPost(id) } ); And thats why your next callback, known as typeResolver fails and returns you a null. var { nodeInterface, nodeField } = nodeDefinitions( ... (obj) => { ... // here you get Promise/Collection instead of single Post instance, therefore condition failed }else if (obj instanceof Post) { return postType; } return null; } );
LordDave's answer revealed one problem in your code. As you commented in his answer, all_posts field of settingType was not working. If you used mongoose library in your DB code, I see a problem with your query: Post.find({$or: [findTitle,findContent]}).sort({createdAt: 'descending'}).exec({}, function(err, posts) { if (err) { resolve({}) } else { resolve(posts) } }); Based on documentation of exec, change your query to return Post.find({$or: [findTitle,findContent]}).sort({createdAt: 'descending'}).exec(function(err, posts) { if (err) { resolve({}) } else { resolve(posts) } }); As exec returns a promise, you can even do return Post.find({$or: [findTitle,findContent]}).sort({createdAt: 'descending'}).exec();
Finally I got it working by creating a new type 'postList' and defined it as below var { nodeInterface, nodeField } = nodeDefinitions( (globalId) => { var { type, id } = fromGlobalId(globalId); if (type === 'User') { return getUser(id); }else if (type==='postList') { return getpostList(id); } else{ return null; } }, (obj) => { if (obj instanceof User) { return userType; }else if (obj instanceof postList) { return postListType; }else{ return null; } } ); In database.js class postList {} postList.id = "Post_id"; export {postList} export function getpostList(id) { return new postList } and under root fields as below var postListType = new GraphQLObjectType({ name: 'postList', description: 'List of posts', fields: () => ({ id: globalIdField('postList'), posts: { type: postConnection, description: 'List of posts', args: { ...connectionArgs, query: {type: GraphQLString} }, resolve: (_, args) => connectionFromPromisedArray(getAllPosts(_,args), args), }, }), interfaces: [nodeInterface], }); var Root = new GraphQLObjectType({ name: 'Root', fields: () => ({ node: nodeField, postList: { type: postListType, resolve:(rootValue)=> { return getpostList() } }, }) });
I ran into this issue when I was using an InterfaceType and checked for the InterfaceType before the specialized ObjectType in the if-elseif-else of my TypeResolver