猫鼬如何在对象中填充数据

Mongoose how to populate data within an object

我在 Stack Overflow 上阅读了几个关于相同问题的主题 (),但我不知道为什么在我的情况下它根本不起作用。

我有一个用户模型:

const UserSchema = new Schema({
  login: String,
  email: String,
  password: String,
  purchases: [{
    item: {
      type: Schema.Types.ObjectId,
      ref: 'cart'
    },
    quantity: {
      type: Number,
      default: 1
    }
  }
})];

注意购买它是一个对象数组(为什么是对象?因为我需要一个额外的字段 'quantity',所以我在这里被告知如何实现这个)有额外的字段 - 数量。我在 user.purchases 上使用 push 方法来添加新项目,到目前为止它工作得很好。当我尝试在 'purchases' 数组中填充项目时出现主要问题。我尝试了不同的方式:

    User.findById(userId).populate({
        path: 'purchases',
        populate: {
          path: 'item',
          model: 'product'
        }
    })

    User.findById(userId).populate({
        path: 'purchases.item',
        model: 'product',
    })
with and without 'model', was using populate('purchases') and etc., but everything was of no use...I alway get data with _id's of items instead of items data itself.

    {
        "_id": "5b60620689f0872a3010b726",
        "login": "lalal",
        "email": "ololo",
        "password": "hahahah",
        "purchases": [
            {
                "quantity": 1,
                "_id": "5b4b80c73c566508146b563f"
            },
            {
                "quantity": 1,
                "_id": "5b4b80c73c566508146b5640"
            },
            {
                "quantity": 1,
                "_id": "5b4b80c73c566508146b5643"
            }
        ],
        "__v": 3
    }

What I'm doing wrong, or maybe I made a mistake with a schema itself?

UPD.: 我做了单文件测试,结果相同,但现在整个代码都在这里。有人可以修复或解释这段代码有什么问题吗? :

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    name: String,
    age: Number,
    items: [{
        buy: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'product'
        },
        quantity: {
            type: Number,
            default: 1
        }
    }]
});

const ProductSchema = new Schema({
    title: String,
    price: Number
});

const Product = module.exports.product = mongoose.model('product', ProductSchema);
const User = module.exports.user = mongoose.model('user', UserSchema);


const newProduct = new Product({
    title: 'Ferrari',
    price: 10000
});

const newUser = new User({
    name: 'Jim',
    age: 20
});

newUser.items.push(newProduct);
newUser.save().then(async () => {
    const data = await User.findOne({name: 'Jim'})
        .then(user => {
            return user.populate({
                path: 'items',
                populate: {
                    path: 'buy',
                    model: 'product'
                }
            });
        });
    console.log(data);
});

mongoose.connect('mongodb://127.0.0.1:27017/megatest')
    .then(() => {
        mongoose.connection.collections.users.drop();
    });

好吧,让我们这样理解模型吧。

user.js

const mongoose = require('../database/index')
const UserSchema = new mongoose.Schema({
    login: String,
    email: String,
    password: String,
    purchases: [{
      item: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Cars'
      },
      quantity: {
        type: Number,
        default: 1
      }
    }]
})

module.exports = mongoose.model('User', UserSchema)

cars.js

const mongoose = require('../database/index')
const carSchema = new mongoose.Schema({
    name:{
        type: String
    },
    tipo: {
        type: String
    }
})

module.exports = mongoose.model('Cars', carSchema)

由于该项目是购买列表,所以它不会仅仅通过说它是购买来填充。

app.get('/busca', async (req, res) => {
    const user = await User.findById({_id:'5b6090516311531fd0b3daaa'}).populate('purchases.item')
    res.send(user)
})

重点来了,说说对于人气猫鼬的购买清单。 .populate('purchases.item')

Result

{
    "_id": "5b60927c79a13f1c98b0aca9",
    "login": "adm",
    "email": "example@example.com",
    "password": "123456",
    "purchases": [
        {
            "quantity": 1,
            "_id": "5b60927c79a13f1c98b0acaa",
            "item": {
                "_id": "5b60927379a13f1c98b0aca8",
                "name": "ferrari",
                "tipo": "sedan",
                "__v": 0
            }
        }
    ],
    "__v": 0
}

EDIT: In this way too populates correct, choosing some item in the search.

app.get('/busca', async (req, res) => {
    //const user = await User.findById({_id:'5b60927c79a13f1c98b0aca9'}).populate('purchases.item', 'tipo')
    const user = await User.findById({_id:'5b60927c79a13f1c98b0aca9'}).populate({
        path: 'purchases.item',
        select: 'name'
    })
    res.send(user)
})

我设法找到了解决方案。这非常简单 - 我只需要填充 ('purchases._id')!!确保您提供的路径是 _id,而不是 'items'、'product' 或您使用的任何名称