简体   繁体   中英

Mongoose: Find from reference object document

I am trying to search data from collection.

Model for 'USER' collection:

var model = new Schema({
    userName: String,
    password: String
});
module.exports = mongoose.model('user', model);

Model for 'BLOG'

var model = new Schema({
    title: String,
    createdBy: { type: Object, ref: 'user' }
});
module.exports = mongoose.model('blog', model);

My search code for blog collection:

objModel.find({ 'createdBy.userName': 'test_user' }).populate('createdBy')
.exec(function (err, lstBlog) {
    console.log(lstBlog.length);
});

But not able to get any record. There are 2 record in database for 'test_user'.

You need to make some changes in your 'BLOG' model :


var mongoose = require('mongoose');
var SCHEMA = mongoose.Schema;

var model = new Schema({
    title: String,
    createdBy: { type: SCHEMA.Types.ObjectId, ref: 'user' }
});

module.exports = mongoose.model('blog', model);


and then the following query will work

blog.find({}).populate(
      {
        path: 'createdBy',
        match: {'userName': 'test_user' }
      }
    ).exec(function (err, lstBlog) {
    console.log(lstBlog.length);
});;

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