sebelga / gstore-node

Google Datastore Entities Modeling for Node.js
Apache License 2.0
292 stars 53 forks source link

Could not find gstore instance with id "${id}" #237

Closed raniceyue closed 3 years ago

raniceyue commented 4 years ago

Hello, I am trying to use gstore-node to create an API for a web application.

Right now, in my server.ts, I have the following code to connect my gstore to

const { Gstore, instances } = require('gstore-node');
const { Datastore } = require('@google-cloud/datastore');

const datastore = new Datastore({ projectId: 'my-project-id' });
const gstore = new Gstore();
gstore.connect(datastore);

instances.set('listings', gstore);

and in my model.ts, I have the following code:

const { instances } = require('gstore-node');

const gstore = instances.get('listings');
const Schema = gstore.Schema;

const listingSchema = new Schema({
    owner: { type: String },
    title: { type: String },
    price: { type: Number },
    deposit: { type: Number },
    description: { type: String},
    condition: { type: String, values: ["brand new", "heavily used", "lightly used"]},
    category: { type: Array, optional: true },
    isAvail: { type: Boolean, default: false }
});

// Settings for listing out entities

const listSettings = {
    limit: 15,
    order: { property: 'title'}
};

listingSchema.queries('list', listSettings);

module.exports = gstore.model('Listings', listingSchema);

Both my model.ts and server.ts are in the same directory, however whenever I run the server, I get the following error:

...
            throw new Error(`Could not find gstore instance with id "${id}"`);
                  ^
Error: Could not find gstore instance with id "listings"
...

I am not sure what I am missing here as I tried my best to follow the gstore-node documentation as much as possible, is there something I'm missing out?

sebelga commented 3 years ago

Hello, Sorry for the late answer. It seems that the model.ts is imported before the server.ts. Is that possible? You might not need to uses instances if you only have 1. So you could simply have a db.ts file

// db.ts

const { Gstore, instances } = require('gstore-node');
const { Datastore } = require('@google-cloud/datastore');

const datastore = new Datastore({ projectId: 'my-project-id' });
const gstore = new Gstore();
gstore.connect(datastore);

module.exports = {
  gstore,
};

And then import it in your model.ts

const { gstore } = require('./db');

const Schema = gstore.Schema;

...

Let me know if this works for you.

sebelga commented 3 years ago

I will close the issue for inactivity. Feel free to re-open if the issue persists.