I have a problem where I am creating a user and want to save some items associated to this user at the same time.
I have managed to get it where I can create an item and reference the user_id associated to that item but I cant work out how to push all the items the user has into the User schema.
I have tried looping through req.body.taken and adding to user schema but I just get null returned.
router.post('/data', async (req, res) => {
var user = new User({
name: req.body.name,
website: req.body.website,
})
user.save(function (err) {
if (err) {
return next(err);
}
})
req.body.taken.forEach((item) => {
var item = new Item({
x: item.x,
y: item.y,
xSize: item.xSize,
ySize: item.xSize,
user: user,
imageSource: item.imageSource,
user: user
}
)
item.save(function (err) {
if (err) {
return next(err);
}
})
})
const UserSchema = new Schema(
{
id: Number,
name: String,
website: String,
items: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Item'
}]
},
{ timestamps: true }
);
const ItemSchema = new Schema(
{
id: Number,
x: Number,
y: Number,
xSize: String,
ySize: String,
imageSource: String,
user: { type: mongoose.Schema.ObjectId, ref: 'User' }
},
{ timestamps: true }
);
User.find({})
.populate('items')
.exec(function(error, items) {
console.log(items)
})
When I call User find I want to get all items associated to that user (which will be an array as req.body.taken is an array of items.
var item =use different variable name here because hoisting will create problem.