【发布时间】:2018-08-02 19:11:28
【问题描述】:
我在 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();
});
【问题讨论】:
-
通过
type: mongoose.Schema.Types.ObjectId更改模型类型并进行测试。 -
另一个细节,你如何实例化猫鼬?我看到
const UserSchema = new Schema({可以看到其余的猫鼬代码。 -
我要测试你的模型,然后告诉你。
-
测试显示相同的结果。用户模型实例化: const User = module.exports = mongoose.model('user', UserSchema); Products: const ProductSchema = new Schema({ title: String, description: String, product_type: String, image_tag: String, created_at: Number, price: Number }); const Product = module.exports = mongoose.model('product', ProductSchema);和一堆代表端点的代码