I’m learning MongoDB/Mongoose by the docs and I’m trying to insert the second collection into the first collection, I know how to do it by using $lookup in mongo terminal, but I kind of confuse how to do it the same in mongoose. I’ve already tried populate() but it didn’t work either.
First Schema
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
useremail: {
type: String,
required: true
},
password: {
type: String,
required: true
},
phone: {
type: String,
required: true
},
detail: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'Detail'
}
});
module.exports = mongoose.model('User', userSchema, 'users');
Second Schema
const mongoose = require('mongoose');
const detailsSchema = mongoose.Schema({
full_name: {
type: String,
required: true
},
birthday: {
type: String,
required: true
},
second_contact: {
type: Number,
required: false
},
gender: {
type: String,
required: true
},
user: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'User',
required: true
}
});
The route
const express = require('express');
const router = express.Router();
const Users = require('../models/user');
const Detail = require('../models/details');
router.post('/register', async(req, res) => {
const { useremail, password, phone, full_name, birthday, gender } = req.body;
try {
let user = await Users.create({ useremail, password, phone });
Users.findOne({ useremail }).populate('detail');
} catch (err) {
res.status(422).send(err);
console.log(err);
}
});
module.exports = router;
What I want is to create a new user along with its detail