KeystoneJS get ObjectID from another value

798 views Asked by At

I want to get the ObjectID from a category by using slug path (key)

this is the model (its the default from keystone generator)

var keystone = require('keystone');

/**
 * PostCategory Model
 * ==================
 */

var PostCategory = new keystone.List('PostCategory', {
    autokey: { from: 'name', path: 'key', unique: true },
});

PostCategory.add({
    name: { type: String, required: true },
});

PostCategory.relationship({ ref: 'Post', path: 'categories' });

PostCategory.register();

Heres what i get from mongoshell

db.getCollection('postcategories').find({"key":"test"})

{
    "_id" : ObjectId("5853a502455e60d5282d9325"),
    "key" : "test",
    "name" : "test",
    "__v" : 0
}

This is just to find if the key works
but when i use this on routes

var gc = "test";
var c = keystone.list('PostCategory').model.find().where('key').equals(gc);
 c.key = gc;
console.log(gc ,c.id);

The log says test undefined.
i tried to use postcategories as well but it says keystone doesnt recognize it

2

There are 2 answers

2
Jake Stockwin On BEST ANSWER

Let's pick up our discussion from your keystone issue here.

The reason should be that find() returns a Promise, so the operation is ran asynchronously. Therefore, at the moment you log the value, it's still undefined.

There are examples of the promises on the keystone demo site, for example here.

I think what you want is something like:

var gc = "test";
var c = keystone.list('PostCategory').model.find().where('key').equals(gc).exec(function (err, results) {
    if (err) {
        console.log(err);
    } else {
        console.log(results);
    }
});

or

keystone
   .list('PostCategory')
   .model
   .find()
   .where('key')
   .equals(gc)
   .then(function(category) {
      console.log(category.id);
});

Also, I'm not sure here but if find({"key":"test"}) works in mongoshell, it might also work in mongoose, so have you tried keystone.list('PostCategory').model.find({"key":"test"}).exec(...)?

4
enRaiser On
var gc = test; ?????

obviously test is not defined. from Javascript perspective. JS expects test to be a variable. and it dont know what is DB at that moment.