te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - How should I properly use populate with mongoose? - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How should I properly use populate with mongoose? - Stack Overflow

programmeradmin4浏览0评论

I am learning some node and have been trying to use mongoose. Currently, my goal is to learn how to use populate.

I have a projects definition and milestone require:

projectSchema = new mongoose.Schema({
    id: String,
    title: String,
    description: String,
    owner: String,
    site: String,
    creation_date: Date,
    milestone_ids: Array,
    milestones: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Milestone"
    }]
})

Project = mongoose.model("Project", projectSchema)
milestones = require(__dirname + "/milestones.js")();

Then I do this at some point in the projects.js:

Project.find(query, {}, {sort: {_id: -1}},
    function (error, results) {
        callback(results);
    }
).populate("milestones");

How do I populate the milestones?


Here is the project data from mongo:

{
    "title": "sitename",
    "description": "online thing",
    "creation_date": {
        "$date": "2013-07-11T19:45:42.139Z"
    },
    "_id": {
        "$oid": "51df0b66dbdd7c4f14000001"
    },
    "milestones": [],
    "milestone_ids": [],
    "__v": 0
}

And this one is the milestone that is basically connected to the project:

{
    "title": "Proof of concept",
    "description": "Make it work.",
    "due_date": {
        "$date": "2013-07-11T19:46:38.535Z"
    },
    "project_id": "51df0b66dbdd7c4f14000001",
    "_id": {
        "$oid": "51df0b9edbdd7c4f14000002"
    },
    "__v": 0
}

Also, this is the milestone schema:

milestoneschema = new mongoose.Schema({
    id: String,
    title: String,
    description: String,
    owner: String,
    site: String,
    due_date: Date,
    project_id: {
        type: String,
        ref: "Project"
    }
})

Milestone = mongoose.model("Milestone", milestoneschema);

I am learning some node and have been trying to use mongoose. Currently, my goal is to learn how to use populate.

I have a projects definition and milestone require:

projectSchema = new mongoose.Schema({
    id: String,
    title: String,
    description: String,
    owner: String,
    site: String,
    creation_date: Date,
    milestone_ids: Array,
    milestones: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Milestone"
    }]
})

Project = mongoose.model("Project", projectSchema)
milestones = require(__dirname + "/milestones.js")();

Then I do this at some point in the projects.js:

Project.find(query, {}, {sort: {_id: -1}},
    function (error, results) {
        callback(results);
    }
).populate("milestones");

How do I populate the milestones?


Here is the project data from mongo:

{
    "title": "sitename",
    "description": "online thing",
    "creation_date": {
        "$date": "2013-07-11T19:45:42.139Z"
    },
    "_id": {
        "$oid": "51df0b66dbdd7c4f14000001"
    },
    "milestones": [],
    "milestone_ids": [],
    "__v": 0
}

And this one is the milestone that is basically connected to the project:

{
    "title": "Proof of concept",
    "description": "Make it work.",
    "due_date": {
        "$date": "2013-07-11T19:46:38.535Z"
    },
    "project_id": "51df0b66dbdd7c4f14000001",
    "_id": {
        "$oid": "51df0b9edbdd7c4f14000002"
    },
    "__v": 0
}

Also, this is the milestone schema:

milestoneschema = new mongoose.Schema({
    id: String,
    title: String,
    description: String,
    owner: String,
    site: String,
    due_date: Date,
    project_id: {
        type: String,
        ref: "Project"
    }
})

Milestone = mongoose.model("Milestone", milestoneschema);
Share Improve this question edited Mar 9, 2016 at 19:16 Kyll 7,1498 gold badges44 silver badges64 bronze badges asked Jul 11, 2013 at 16:26 eduardeduard 1,4953 gold badges13 silver badges29 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

You need to get the order right of defining query options then executing, and chainable APIs such as mongoose Query can't know what additional methods you might call AFTER the query fires. So when you pass the callback to .find, mongoose sends the query right away.

Pass a callback to find

  • query defined by arguments to find
  • since callback is there, query immediately executes and issues mand to DB
  • then .populate happens, but it has no effect as the query has already been sent to mongo

Here's what you need to do:

Project.find(query, {}, {
    sort: {
        _id: -1
    }
}).populate("milestones").exec(function (error, results) {
    callback(results);
});

Or a little more readable:

Project
    .find(query)
    .sort('-_id')
    .populate('milestones')
    .exec(function(error, results) {                  
        callback(results);
    });

Omit callback and use .exec

  • query passed to .find creates query object with parameters
  • additional chained calls to .sort, .populate etc further configure the query
  • .exec tells mongoose you are done configuring the query and mongoose issues the DB mand
发布评论

评论列表(0)

  1. 暂无评论