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

时间:2018-07-31 14:08:28

标签: mongoose populate

我在此处阅读了关于Stack Overflow的几个主题,并提出了相同的问题(How to populate in this case Mongoose),但我不知道为什么在我看来,它根本不起作用。

我有一个用户模型:

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

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

    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();
    });

2 个答案:

答案 0 :(得分:0)

让我们以这种方式获得模型。

  

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')

  

结果

{
    "_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
}
  

编辑:   这样也可以正确填充,在搜索中选择一些项目。

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)
})

答案 1 :(得分:0)

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