Closed isaac8069 closed 2 years ago
Are you having trouble creating the apartments and tags simultaneously, or accessing the data afterwards?
apartments and tags are created. how to associate? I could have done a findOrCreate tag and associated to the apartment as well. Wasn't sure the best approach
This was the findOrCreate route...i made some changes but more or less this was it
req.body.tag.apartments.push(req.params.apartmentId)
Tag.findOrCreate(req.body.tag)
// respond to succesful `create` with status 201 and JSON of new "tag"
.then((tag) => {
console.log('THIS IS FOUND TAG', tag)
apartment.findById(req.params.apartmentId)
.then(foundApartment => {
foundApartment.tags.push(tag._id)
foundApartment.save()
res.status(201).json({ tag: tag.toObject() })
})
})
.catch(next)
Ah, yeah i mean that looks right to me. The only association you need is the reference Id for tag being stored somewhere in the apartment object. Have you had a chance to test it?
User = apartment Bundle = tag
This is the code for this route:
// POST /apartmentId/tags
router.post('/add-tag/:id', requireToken, (req, res, next) => {
const apartmentTag = (req.body.tag)
apartment.findById({ _id: req.params.id })
.exec()
.then(handle404)
.then(apartment => {
// requireOwnership(req, tag)
const tag = new Tag({
apartmentTag
})
tag.save()
.then(tag => {
console.log('THSI IS THE TAGid', tag._id)
apartment.tags.push(tag._id)
apartment.save()
.then((apartment) => res.status(200).json(apartment))
.catch(next)
})
})
})
Updated error message
// UPDATE
// POST /add-tag/apartmentId
router.post('/add-tag/:id', requireToken, (req, res, next) => {
const apartmentTag = (req.body.tag)
apartment.findById({ _id: req.params.id })
.exec()
.then(handle404)
.then(apartment => {
const tag = new Tag({
apartmentTag
})
tag.save()
.then(tag => {
// requireOwnership(req, tag)
console.log('THSI IS THE TAGid', tag._id)
apartment.tags.push(tag._id)
apartment.save()
.then((apartment) => res.status(200).json(apartment))
.catch(err => res.status(400).json('Error on tag save: ' + err))
})
})
.catch(next)
})
push the tag, not the id
Gonna close this. First write a post route for apartments, and a post route for tags, before working on associating them :)
What stack are you using?
(ex: MERN(mongoose + react), DR(django + react), PEN, etc.)
MERN
What's the problem you're trying to solve?
I cant figure out how to make n to n associations / model needs another lookover
Post any code you think might be relevant (one fenced block per file)
If you see an error message, post it here. If you don't, what unexpected behavior are you seeing?
What is your best guess as to the source of the problem?
Not sure. Its structured to create tag and apartment separately at the moment then the association happens
What things have you already tried to solve the problem?
Apartment.findByIdAndUpdate(apartmentId, {