Keystonejs从另一个值中获取ObjectID



我想通过使用slug路径(键)

从类别中获取objectid

这是模型(是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();

我从蒙古尔(Mongoshell)那里得到的东西

db.getCollection('post类别')。查找({"键":" test"})

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

这只是为了找到键是否有效
但是当我在路线上使用它

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

日志说的测试未定义。
我也试图使用邮政分类,但它说Keystone不认识它

让我们从您的Keystone问题中获取我们的讨论。

原因是find()返回承诺,因此该操作是异步运行的。因此,目前登录值,它仍然是undefined

例如,在这里,有一些承诺的示例。

我认为您想要的是:

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);
    }
});

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

另外,我不确定在这里,但是如果find({"key":"test"})在Mongoshell中起作用,它也可能在Mongoose中起作用,所以您是否尝试过keystone.list('PostCategory').model.find({"key":"test"}).exec(...)

var gc = test; ?????

显然未定义测试。从JavaScript的角度来看。JS期望测试是一个变量。而且它不知道当时是什么DB。

最新更新