嗨,我对后端相当陌生。我正试图将一个新的Comment添加到一个评论列表中,但得到了updatedTravelTips null。我哪里做错了?我应该瞄准哪个mongo_id?我知道我的数据库中嵌套的对象有点乱。。。这就是我的用户在mongoDBcompass中的样子:
https://i.stack.imgur.com/moncj.png
const onTravelTips = (event) => {
event.preventDefault()
const options = {
method: 'PATCH',
headers: {
Authorization: accessToken,
'Content-Type': 'application/json'
},
// neWcomment comes from a text input in a form
body: JSON.stringify({ comments: newComment })
}
//countryId comes from selected country from a dropdown and stored in state
fetch(API_URL(`countries/${countryId}`), options)
.then(res => res.json())
.then(data => {
if (data.success) {
console.log(data)
dispatch(user.actions.setErrors(null))
} else {
dispatch(user.actions.setErrors({ message: 'Failed to add travel tips' }))
}
})
}
<form className="add-tips-form">
<p>Choose one of your visited countries and add some tips:</p>
<select value={newCountryId} onChange={(event) => dispatch(user.actions.setCountryId(event.target.value))}>
<optgroup label='Countries'>
<option value="" disabled defaultValue>Select country</option>
{visitedList && visitedList.map(country => (
<option
key={country.country._id}
// country._id gets the new one, country.country._id gets the countryid
value={country._id}
>{country.country.country} {console.log(country._id)}</option>
))}
</optgroup>
</select>
<input
type="text"
value={newComment}
onChange={(event) => setNewComment(event.target.value)}
className="username-input"
placeholder="food"
/>
<button className="add-tips-button" onClick={onTravelTips}>Add travel tips</button>
</form>
const Country = mongoose.model('Country', {
country: String,
alphaCode: String,
})
const User = mongoose.model('User', {
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true
},
accessToken: {
type: String,
default: () => crypto.randomBytes(128).toString('hex')
},
visitedCountries:[ {
country: {
type: Object,
ref: "Country",
},
comments: Array
}]
})
app.patch('/countries/:countryid', authenticateUser)
app.patch('/countries/:countryid', async (req, res) => {
const { countryid } = req.params
const { comments, } = req.body
const {id} = req.user
try {
console.log(countryid) // working, gets the country id or the nested object id depening on what we pass in FE
console.log(comments) // working, gets whatever we write in text input. *should it be so?
console.log(id) // working, gets user id
console.log("comment",newComment) // not working, return undefined
const updatedTravelTips = await User.findOneAndUpdate( {id, countryid, comments }, {
$push: {
visitedCountries: { comments: comments}
},
}, { new: true })
res.json({ success: true, updatedTravelTips })
console.log(updatedTravelTips) // not working, return null
} catch (error) {
res.status(400).json({ success: false, message: "Invalid request", error })
}
})
app.patch('/countries/:countryid', authenticateUser)
app.patch('/countries/:countryid', async (req, res) => {
const { countryid } = req.params
const { comments, } = req.body
const {id} = req.user
try {
const updatedTravelTips = await User.findOneAndUpdate( {_id: id, "visitedCountries._id": countryid }, {
$push: {
"visitedCountries.$.comments": comments
},
}, { new: true })
res.json({ success: true, updatedTravelTips })
} catch (error) {
res.status(400).json({ success: false, message: "Invalid request", error })
}
})