So, I was trying out typescript, in the mongoose website i could see guide for typescript, to analyize the code, I copied a snippet from the official documentation.
import { Document, Model, Query, Schema, connect, model } from 'mongoose';
interface Project {
name: string;
stars: number;
}
const schema = new Schema<Project>({
name: { type: String, required: true },
stars: { type: Number, required: true }
});
// Query helpers should return `Query<any, Document<DocType>> & ProjectQueryHelpers`
// to enable chaining.
interface ProjectQueryHelpers {
byName(name: string): Query<any, Document<Project>> & ProjectQueryHelpers;
}
// The error is on the below line, it says Property 'byName' does not exist on type '{}'
schema.query.byName = function(name): Query<any, Document<Project>> & ProjectQueryHelpers {
return this.find({ name: name });
};
// 2nd param to `model()` is the Model class to return.
const ProjectModel = model<Project, Model<Project, ProjectQueryHelpers>>('Project', schema);
run().catch(err => console.log(err));
async function run(): Promise<void> {
await connect('mongodb://localhost:27017/test');
// Equivalent to `ProjectModel.find({ stars: { $gt: 1000 }, name: 'mongoose' })`
await ProjectModel.find().where('stars').gt(1000).byName('mongoose');
}
I am not sure why this error has occured, can someone help me out? When inspecting the schema object I could see the query was { }. But why so?
I think that your problem is a typescript version, I am using v4.5.4 and everthing ok.
try this, please:
(schema as Schema<Project> & { query: ProjectQueryHelpers }).query.byName = function (
name: string
): Query<any, Document<Project>> & ProjectQueryHelpers {
return this.find({ name: name });
};