【问题标题】:Mongoose: utils.populate: invalid path. Expected string. Got typeof 'undefined'猫鼬:utils.populate:路径无效。预期的字符串。得到类型'未定义'
【发布时间】:2017-07-07 18:11:45
【问题描述】:

我不是一个全新的填充用户,但现在我不知道出了什么问题。

在这里我需要填充我的 designerId,它是 ObjectId 的类型。看看我的路线。

ordersAdminRouter.route('/customorder/add')
    .post(function(req, res){
        body = req.body;
        console.log(body);
        CustomOrders.create(body, function(err, saved){
            if (err) throw err;
            Designs.findByIdAndUpdate(saved.designId, {$set: {status: 'Order Sent'}}, {new: true}).exec()
                .then(function(updated){
                    return CustomOrders.findById(saved._id).populate(saved.designId).exec();
            })
            .then(function(orders){
                res.json(orders);
            })
            .then(undefined, function(err){
                console.log(err);
            })
        });
    });

saved._id 正在工作,因为当我删除填充时,它会返回我需要的文档,当然没有填充的文档。

看看我的架构

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

var customOrderSchema = new Schema({
    designId: { type: Schema.Types.ObjectId, ref: 'customDesigns' },
    size: { type: String },
    quantity: { type: Number },
    totalPrice: { type: Number },
    paymentMode: { type: String },
    rcpt_img: { type: String },
    refNumber: { type: String }
});

module.exports = mongoose.model('customOrders', customOrderSchema);

这是我的customDesigns 架构。

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

var customDesignSchema = new Schema({
    item_name: { type: String },
    price: { type: Number, default: 0 },
    img_url_front: { type: String },
    img_url_back: { type: String },
    designer: { type: Schema.Types.ObjectId, ref: 'users' },
    color: { type: String },
    designDate: { type: Date, default: Date.now() },
    status: { type: String, default: 'For Qoutation' }
});

module.exports = mongoose.model('customDesigns', customDesignSchema);

我需要承认我对 mongoose & express 的 promises 不熟悉,这是我第一次这样做。但是使用填充,我使用它的次数超出了我的想象。有什么建议吗?

【问题讨论】:

    标签: node.js mongodb express mongoose promise


    【解决方案1】:
    return CustomOrders.findById(saved._id).populate('designId').then(.. your code);
    

    顺便说一句,你不必使用.exec() 然后你想执行你的查询,.then 也执行查询。你可以跳过.exec()

    http://mongoosejs.com/docs/populate.html

    http://mongoosejs.com/docs/api.html#query_Query-populate

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      • 2017-12-24
      • 2017-07-25
      • 2021-07-15
      • 2021-12-03
      • 2018-12-27
      相关资源
      最近更新 更多