sebelga / gstore-node

Google Datastore Entities Modeling for Node.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Populate not working as shown in the examples

mknosens opened this issue · comments

I followed your examples for populate:

const userSchema = new Schema({ name: { type: String } });
const postSchema = new Schema({ title: { type: String }, user: { type: Schema.Types.Key, ref: 'User' } });
const User = gstore.model('User', userSchema);
const Post = gstore.model('Post', postSchema);

// create records
const user = new User({ name: 'John' });
await user.save();
const post = new Post({ title: 'Title of the post', user: user.entityKey });
await post.save();

//fetch
const post1 = await Post.get(<post_id>).populate('User');
console.log(post1);

Expected response as per your document:

{
    title: 'Title of the post',
    user: {
      name: 'John',
    }
}

But I got this response, where format is not the same and User is null.

GstoreModel {
  entityData: {
    title: 'Title of the post',
    user: Key {
      namespace: undefined,
      id: '5754152319713280',
      kind: 'User',
      path: [Getter]
    },
    User: null,
    [Symbol(KEY)]: Key {
      namespace: undefined,
      id: '5687085298089984',
      kind: 'Post',
      path: [Getter]
    }
  },
  __hooksEnabled: true,
  __className: 'Entity',
  __excludeFromIndexes: {},
  context: {},
  entityKey: Key {
    namespace: undefined,
    id: '5687085298089984',
    kind: 'Post',
    path: [Getter]
  },
  pre: [Function: pre],
  post: [Function: post],
  hook: [Function: hook],
  __setupHooks: [Function: __setupHooks]
}

Am I missing something? I checked the database and it is correctly showing Post with Reference to the User John.

Hello, you have to provide the property name (“user” lowercase) to the populate function, and not the model name.

Well that was a stupid mistake on my part. Thanks for pointing that out.
But the response format is still a lot different than just a json output. I tried using .plain() and the response still has extra information like:

{
  id: '5696928490717184',
  title: 'Title of the post',
  user: {
    id: '5106940979970048',
    name: 'John',
    [Symbol(KEY)]: Key {
      namespace: undefined,
      id: '5106940979970048',
      kind: 'User',
      path: [Getter]
    }
  },
  [Symbol(KEY)]: Key {
    namespace: undefined,
    id: '5696928490717184',
    kind: 'Post',
    path: [Getter]
  }
}

Is it possible to keep it as simple as:

{
    id: '5696928490717184',
    title: 'Title of the post',
    user: {
      name: 'John',
    }
}

Hello,

The [Symbol] is the Key that is added by the Datastore client and will be stripped out when passing the object through an HTTP request.

If you really don't want the id property to appear, I would suggest adding a serializer that removes the property from the object, as if gstore-node does not add it anymore it would be a breaking change for a lot of people.

Cheers.

Thanks for the explanation!