如何解决在MERN Stack中更新架构
我有一个用户模式模型,其中(应该)通过地址模式模型填充address
字段。为了更新地址架构,我已经在请求正文中传递了该地址架构,并通过从userId
中提取用户ID填充了req.user
字段。我可以在地址字段中添加新条目,但是当我在Atlas中查看用户模型时,它并未填充。
我的假设是,它将根据用户的ID自动填充该信息,但事实并非如此。我会做错吗?
路线:
const addAddress = async (req,res) => {
try {
console.log(req.body);
// Destruct Request
const { name,street,city,state,zipcode } = req.body;
// Define User ID
const user = req.user.id;
const addUserAddress = await User.findById(user,(error,address) => {
if (error) {
return res
.status(500)
.json({ success: false,message: 'An unexpected error occurred.' });
}
let newAddress = new Address({
_userId: user,name,zipcode,});
newAddress.save((err0r) => {
if (error) {
return res
.status(500)
.json({ success: false,message: 'An unexpected error occurred.' });
}
});
});
res.json(addUserAddress);
} catch (error) {
console.error(error);
res.status(500).send('Error adding an address,please try again.');
}
};
地址模型:
const AddressSchema = new mongoose.Schema({
_userId: {
type: ObjectId,required: true,ref: 'User',},name: {
type: String,unique: false,street: {
type: String,city: {
type: String,state: {
type: String,zipcode: {
type: String,});
const Address = mongoose.model('Address',AddressSchema);
exports.Address = Address;
用户模型:
const UserSchema = new mongoose.Schema({
...
address: [
{
type: ObjectId,ref: 'Address',],...
});
解决方法
已插入ID,但不会自动填充信息。为了填充信息,您必须执行以下操作……
const usersWithAddress = await User.find({}).populate("address","city state zip",Address) // Pass in the Address model as the 3rd argument.
Populate可以在没有Address模型的情况下工作,但是过去我在没有传递它的时候遇到了问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。