简体   繁体   中英

How nested query relational data in keystone.js(mongoose)?

This is my data structure, I want to implement a relational query, but the query is nested data fields.I know after reading mongoose document the basic usage of nested queries, but when I tested but nothing returns.Please help me, I will be grateful.

//Define
var TimeLine = new keystone.List('TimeLine', {
    hidden:true
});
TimeLine.add({
    article:{type:Types.Relationship,ref:'Post'}
});

var Post = new keystone.List('Post', {
    map: { name: 'title' },
    autokey: { path: 'slug', from: 'title', unique: true }
});

Post.add({
    title: { type: String, required: true },
    state: { type: Types.Select, options: 'draft, published, archived', default: 'draft', index: true },
    author: { type: Types.Relationship, ref: 'User', index: true },
    publishedDate: { type: Types.Date, index: true, dependsOn: { state: 'published' } },
    image: { type: Types.CloudinaryImage },
    content: {
        brief: { type: Types.Html, wysiwyg: true, height: 150 },
        extended: { type: Types.Html, wysiwyg: true, height: 400 }
    }
});
//Usage

var timeline = keystone.list('TimeLine').model;
    timeline.find({
        "article.title":"xxxxxxxxx"//Here is a nested query
    }).populate('article').exec(function (err, result) {
        console.log(err,result);//This is the query results, but it can not return anything.
    });

//nothing return!!!

Unfortunately, what you're trying to accomplish is not possible with Mongoose. There are no joins in MongoDB or Mongoose. Populating references is the closest equivalent.

When populating a relationship, Mongoose first resolve the query then populates the referenced collection based on the documents found in the initial query. This means you cannot reference fields from the related collection in the initial query.

In your example your trying to reference the title field of the article collection, before the article collection is populated.

timeline.find({
    "article.title":"xxxxxxxxx" // <<-- invalid reference
}).populate('article') ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM