求解mongoose中的populate方法报错
发布于 10 年前 作者 xuyuan923 5346 次浏览 最后一次编辑是 8 年前 来自 问答

直接贴代码: schemas/line.js:

var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;
var LineSchema = new mongoose.Schema({
    creator: {type:ObjectId,ref:'User'},
    title:String,
    desc:String
})

controllers/line.js:

var mongoose = require('mongoose');
var Line = require('../models/line');
var User = require('../models/user');
exports.detail = function (req, res) {
    var id = req.params.id;
    Line.findById(id, function (err, line) {
        User
            .findById(req.session.user._id)
            .populate('creator','name')
            .exec(function(err,users){
                console.log('users:');
                console.log(users);
                res.render('lineDetail', {
                    title: line.title,
                    line: line,
                    users: users
                })
            })
    })
};

模板jade文件是:

 					dt 业务名称
                    dd #{line.title}
                    dt 创建时间
                    dd #{line.meta.createAt}
                    dt 创建人
                    dd #{line.creator.name}
                    dt 业务介绍
                    dd #{line.desc}

报错信息:

/Users/cassie/github-demo/mean/app/controllers/line.js:15
            .populate('creator','name')
             ^
TypeError: Object #<Promise> has no method 'populate'
    at Promise.<anonymous> (/Users/cassie/github-demo/mean/app/controllers/line.js:15:14)
    at Promise.<anonymous> (/Users/cassie/github-demo/mean/node_modules/mongoose/node_modules/mpromise/lib/promise.js:177:8)
    at Promise.emit (events.js:95:17)
    at Promise.emit (/Users/cassie/github-demo/mean/node_modules/mongoose/node_modules/mpromise/lib/promise.js:84:38)
    at Promise.fulfill (/Users/cassie/github-demo/mean/node_modules/mongoose/node_modules/mpromise/lib/promise.js:97:20)
    at Promise.resolve (/Users/cassie/github-demo/mean/node_modules/mongoose/lib/promise.js:114:23)
    at Promise.<anonymous> (/Users/cassie/github-demo/mean/node_modules/mongoose/node_modules/mpromise/lib/promise.js:177:8)
    at Promise.emit (events.js:95:17)
    at Promise.emit (/Users/cassie/github-demo/mean/node_modules/mongoose/node_modules/mpromise/lib/promise.js:84:38)
    at Promise.fulfill (/Users/cassie/github-demo/mean/node_modules/mongoose/node_modules/mpromise/lib/promise.js:97:20)

不知道哪里错了,求大大解释。

4 回复

自己顶一下,求解。

User.findById(...).populate改成Line.findById(...).populate试试。

@pockry 试过了,改成这样还是报同样地错误。

    var id = req.params.id;
    User.findById(req.session.user._id, function (err, users) {
        Line
            .findById(id)
            .populate('creator','name')
            .exec(function(err,line){
                res.render('lineDetail', {
                    title: line.title,
                    line: line,
                    users: users
                })
            })
    })
};

@xuyuan923 不应该啊,你的mongoose版本是多少?

回到顶部