Mongoose如何在对象中填充数据

oiopk7p5  于 2023-08-06  发布在  Go
关注(0)|答案(3)|浏览(90)

我在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
    }
  }
})];

字符串
注意购买它是一个对象数组(为什么是对象?因为我需要一个额外的字段'quantity',所以我被告知在这里SO如何实现这一点),有额外的字段- quantity。我在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();
    });

ijnw1ujt

ijnw1ujt1#

好吧,让我们这样做的模型。
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)
})


这里是重点,为大家说说 Mongoose 的购买清单里面。第一个月
测试结果

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

uqcuzwp8

uqcuzwp82#

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

ef1yzkbh

ef1yzkbh3#

太完美了我只想得到单个值的值,例如。在这个数据中,我想得到的项目名称应该是项目等于名称值。
第一个月

相关问题