admin管理员组文章数量:1122846
I'm working with a Node.js application using MongoDB and Mongoose, and I have two models: User and Address. I am trying to add an address to a user, but when I try to call findOne on the Address model, I get the following error:
TypeError: Cannot read properties of undefined (reading 'findOne')
at C:\path\to\my\project\routes\addresses.js:76:41
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Error Explanation: I am trying to use Address.findOne({ user }) to find the user's address. If the user doesn't have an address, I create a new Address document. However, I am getting the error Cannot read properties of undefined (reading 'findOne'), which suggests that Address is not properly defined or imported.
const express = require('express');
const { Address } = require('../models/address'); // Correct import of the Address model
const router = express.Router();
router.post('/', async (req, res) => {
const { user, fullName, phone, addressLine1, addressLine2, city, state, zip, country, isDefault } = req.body;
try {
let userAddress = await Address.findOne({ user });
if (!userAddress) {
userAddress = new Address({
user,
addresses: [
{ fullName, phone, addressLine1, addressLine2, city, state, zip, country, isDefault },
],
});
} else {
if (isDefault) {
userAddress.addresses.forEach((address) => (address.isDefault = false)); // Unset previous defaults
}
userAddress.addresses.push({ fullName, phone, addressLine1, addressLine2, city, state, zip, country, isDefault });
}
const savedAddress = await userAddress.save();
res.status(200).json({ success: true, message: 'Address added successfully.', data: savedAddress });
} catch (error) {
console.error("Error during address creation:", error);
return res.status(500).json({ success: false, message: 'Failed to create Address.', error: error.message });
}
});
module.exports = router;
Models (address.js):
const mongoose = require('mongoose');
const addressSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
addresses: [
{
fullName: String,
phone: String,
addressLine1: String,
addressLine2: String,
city: String,
state: String,
zip: String,
country: String,
isDefault: Boolean,
},
],
});
const Address = mongoose.model('Address', addressSchema);
module.exports = { Address };
What I've tried so far: I have confirmed that the Address model is correctly imported in my addresses.js file. I have verified the schema of the Address model and ensured that the field user is properly referenced as ObjectId from the User model. I checked the database connection and confirmed that the database is connected.
本文标签:
版权声明:本文标题:node.js - Why am I getting the error Cannot read properties of undefined (reading 'findOne') when trying to add 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736282208a1926569.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论