繁体   English   中英

猫鼬:从参考对象文档中查找

[英]Mongoose: Find from reference object document

我正在尝试从集合中搜索数据。

“ USER”集合的模型:

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

“ BLOG”的模型

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

我的博客收藏搜索代码:

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

但无法获得任何记录。 数据库中有2条'test_user'记录。

您需要在“ BLOG”模型中进行一些更改:


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


然后以下查询将起作用

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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