'Why does model.find() only look for documents within certain collections inside my database?
I am using a tutorial to learn how to use GraphQL and mongoose. I was wondering why when I call .find() on my Post model in my resolver it seems to only return me documents inside collection called 'posts'. If I delete 'posts' collection and change name but copy over exact same documents, my query will return me empty object [].
This is my file containing type definitions
const { gql } = require('apollo-server');
module.exports = gql`
type Post {
id: ID!
body: String!
createdAt: String!
username: String!
}
type User{
id: ID!
email: String!
token: String!
username: String!
createdAt: String!
}
input RegisterInput{
username: String!
password: String!
confirmPassword: String!
email: String!
}
type Query {
getPosts: [Post] #getPosts query
}
type Mutation{
register(registerInput: RegisterInput): User!
}
`;
this is my file that generates the model for posts
const postSchema = new Schema({
body: String,
username: String,
createdAt: String,
comments: [
{
body: String,
username: String,
createDate: String
}
],
likes: [
{
username: String,
createDate: String
}
],
user: {
type: Schema.Types.ObjectId,
ref: 'users'
}
})
module.exports = model('Post', postSchema);
this is my resolver for the previously defined getPost query
const Post = require('../../models/Post');
module.exports = {
Query: {
async getPosts(){ //resolver for getPosts query
try{
const post = await Post.find(); //finds all
return post;
} catch(err) {
throw new Error(err);
}
}
}
}
Solution 1:[1]
I figured it out its because when I created a model using model() the first argument is the collection that the model is designed for.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bob Tin |
