javascript - Node Mongoose 填充条件不返回预期结果

标签 javascript node.js mongodb mongoose

我正在尝试在填充方法中使用查询条件。 如果使用条件,则仍会填充所有记录,但不满足条件的记录会将填充字段设置为空, 例如:

var query = BookModel.find();
query.populate('author','name',{name:'author1'});
query.find(function(err,books){
  console.log(books);
});

Then the output is:
[  { author: { _id: 4ea0db52e09aa6aad2e831fe, name: 'author1' },
    title: 'book1',
    _id: 4ea0dbebc191848704000005 },
  { author: null,
    title: 'book2',
    _id: 4ea0dbebc191848704000006 } ,
  { author: null,
    title: 'book3',
    _id: 4ea0dbebc191848704000007 } ,
  { author: null,
    title: 'book4',
    _id: 4ea0dbebc191848704000008 } ]

但是,我希望输出结果中只有第一条记录。我该如何解决这个问题?

最佳答案

我遇到了与您面临的相同问题,我尝试了上面的代码,但它并没有帮助我解决问题。我找到了一种方法,就像你想要的那样。您不能使用 populate 进行这种过滤,您必须使用 mongodb 的原始查询来过滤数据。

// db['result'] is the name of database
db['result'].aggregate([

    // this is just like populate this populate the user field
    {
        $lookup:{
            from:'users',
            localField:'user',
            foreignField:'_id',
            as:'user'
        }
    },
    // unwind convert the array to objects to apply filter on it
    {
        $unwind:{
            preserveNullAndEmptyArrays : true, // this remove the object which is null
            path : "$user"
        }
    },
    // in match you have to define your condition this check if the user has role equals to 3
    {
        $match:{
            "user.role": 3
        }
    },
    {
        // this provide pagination
        $facet: {
            edges: [
                { $skip: sk },
                { $limit: lm },
            ],
            /* pageInfo: [
                { $group: { _id: null, count: { $sum: 1 } } },
            ],*/
        },
    }
], function (err, result) {
    if (err) {
        // this res is send if there is some error
        console.log(err);
        callback(500, err)
    } else {
        // you get the data
        console.log(result);
        callback(200, result)
    }
});

关于javascript - Node Mongoose 填充条件不返回预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35196620/

相关文章:

javascript - 在jquery中复制由换行符分隔的多个li文本

Node.js 在 typeorm 的实体中添加 created_at 和 updated_at

mongodb Mongoose 连接打开回调没有被调用

node.js - 显示弃用警告 `the server/replset/mongos/db options are deprecated`

javascript - AJAX/jQuery/PHP - AJAX 表单处理程序 "Illegal invocation"

javascript - 如何重命名 react-native 入口文件 (index.ios.js)

node.js - 使用 Node 驱动程序在主机之间克隆 Mongodb 中的数据库

node.js - 如何对sequelize 查询的每个结果进行API 调用?

javascript - MongoDB 和 Node.js 性能中的查询与过滤器

javascript - 在 mailto anchor 标记中发送 HTML