我正在尝试使用mongodb查询.populate()
在分配响应中填充用户数据。
但是我看起来好像没有用。它不是填充用户数据,而是仅填充ID(请查看下面的响应)。我有部落使用“用户”或“用户”,但是当我使用“用户”时,它会将用户返回为空
用户模型
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
allocations: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'allocation'
}],
admin: {
type: Boolean,
default: false
},
date: {
type: Date,
default: Date.now
},
});
module.exports = mongoose.model('users', UserSchema);
分配模型
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const AllocationSchema = new Schema({
name: {
type: String,
default: 'New'
},
jan: {
type: String,
default: 0
},
feb: {
type: String,
default: 0
},
mar: {
type: String,
default: 0
},
apr: {
type: String,
default: 0
},
may: {
type: String,
default: 0
},
jun: {
type: String,
default: 0
},
jul: {
type: String,
default: 0
},
aug: {
type: String,
default: 0
},
sep: {
type: String,
default: 0
},
nov: {
type: String,
default: 0
},
oct: {
type: String,
default: 0
},
dec: {
type: String,
default: 0
},
})
const AllocationsSchema = new Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
refs: 'users'
},
year: {
type: String,
},
allocations: [AllocationSchema],
date: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('allocation', AllocationsSchema);
exports.getAllUsersAndAllocations = async (req, res) => {
try {
let users = await AllocationModel.find({
year: "2019"
}).populate(
'user'
)
return res.json(users)
} catch (error) {
console.error(error.message)
return res.status(500).send('Server error')
}
}
响应:
{
"_id": "5d76ceb0e1fa5c2b6f8f5bed",
"user": "5d7671c446c7ba228ca1382b",
"year": "2019",
"allocations": [
{
"name": "New",
"jan": "0",
"feb": "0",
"mar": "0",
"apr": "0",
"may": "0",
"jun": "0",
"jul": "0",
"aug": "0",
"sep": "0",
"nov": "0",
"oct": "0",
"dec": "0",
"_id": "5d76ceb3e1fa5c2b6f8f5bef"
},
{
"name": "New",
"jan": "0",
"feb": "0",
"mar": "0",
"apr": "0",
"may": "0",
"jun": "0",
"jul": "0",
"aug": "0",
"sep": "0",
"nov": "0",
"oct": "0",
"dec": "0",
"_id": "5d76ceb0e1fa5c2b6f8f5bee"
}
],
"date": "2019-09-09T22:14:08.573Z",
"__v": 1
},
答案 0 :(得分:1)
它看起来可能只是您的AllocationSchema中的错字。在“用户”下,您应将refs: 'users'
写成ref: 'users'
,即用“ ref”代替“ refs”