这里我尝试使用 userId 获取用户创建的地点。这是用户模型和地点模型,在 Controller 中,我编写了通过 userId 获取地点的逻辑。不幸的是,我在 res.json({ }) 方法中发送响应期间收到错误“UnhandledPromiseRejectionWarning: TypeError: place.toObject is not a function”。
地点模型
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const placeSchema = new Schema({
title: { type: String, required: true },
description: { type: String, required: true },
image: { type: String, required: true },
address: { type: String, required: true },
location: {
lat: { type: Number, required: true },
lng: { type: Number, required: true },
},
creator: { type: mongoose.Types.ObjectId, required: true, ref: 'User'}
});
module.exports = mongoose.model('placemodels', placeSchema);
用户模型
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true, minlength: 6 },
image: { type: String, required: true },
places: [{ type: mongoose.Types.ObjectId, required: true, ref: 'Place'}]
});
userSchema.plugin(uniqueValidator);
module.exports = mongoose.model('usermodels', userSchema);
Controller
const getPlacesByUserId = async (req, res, next) => {
const userId = req.params.uid;
let userWithPlaces;
try {
userWithPlaces = await User.findById(userId).populate('placemodels');
} catch (err) {
console.log(err);
const error = new HttpError(
'Fetching places failed, please try again later',
500
);
return next(error);
}
// if (!places || places.length === 0) {
if (!userWithPlaces || userWithPlaces.places.length === 0) {
return next(
new HttpError('Could not find places for the provided user id.', 404)
);
}
res.json({
places: userWithPlaces.places.map(place =>
place.toObject({ getters: true })
)
});
};
最佳答案
引用文献在 Mongoose 填充中非常重要。在模式中,refs
指的是模式的 Mongoose 名称。由于名称为:'placemodels'
和 'usermodels'
。 refs 字段应使用准确的名称。
引用:https://mongoosejs.com/docs/api.html#schematype_SchemaType-ref
第二个重要部分是填充方法的参数。文档指定 populate 函数的第一个参数是名称路径,并且是对象或字符串。在上面的例子中使用了一个字符串。它应该引用要填充的名称字段。
这意味着代码应如下所示,因为我们要填充 places
字段。架构负责知道从哪里获取信息
...
userWithPlaces = await User.findById(userId).populate('places');
...
引用文献:https://mongoosejs.com/docs/api.html#query_Query-populate
关于node.js - UnhandledPromiseRejectionWarning : TypeError: place. toObject 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59842860/