Example 1: mongoose populate
Story.
findOne({ title: /casino royale/i }).
populate('author', 'name').
exec(function (err, story) {
if (err) return handleError(err);
console.log('The author is %s', story.author.name);
console.log('The authors age is %s', story.author.age);
});
Example 2: mongodb populate document
Story.
findOne({ title: 'Casino Royale' }).
populate('author').
exec(function (err, story) {
if (err) return handleError(err);
console.log('The author is %s', story.author.name);
});
Example 3: mongoos populate a ref
const storySchema = Schema({
authors: [{ type: Schema.Types.ObjectId, ref: 'Person' }],
title: String
});
const story = await Story.findOne({ title: 'Casino Royale' }).populate('authors');
story.authors;
Example 4: mongoose referenced schema
const author = new Person({
_id: new mongoose.Types.ObjectId(),
name: 'Ian Fleming',
age: 50
});
author.save(function (err) {
if (err) return handleError(err);
const story1 = new Story({
title: 'Casino Royale',
author: author._id
});
story1.save(function (err) {
if (err) return handleError(err);
});
});
Example 5: mongoose populate
const mongoose = require('mongoose')
const shortid = require('shortid')
mongoose
.connect('mongodb://localhost:27017/mongoose', {
useFindAndModify: false,
useUnifiedTopology: true,
useNewUrlParser: true
})
.then(() => console.log('Connected'))
.catch(() => console.log('Not Connected'))
const CourseSchema = new mongoose.Schema(
{
userId: { type: mongoose.Types.ObjectId },
course: []
},
{ timestamps: true }
)
const Course = mongoose.model('Course', CourseSchema, 'Course')
const UserSchema = new mongoose.Schema(
{
fullName: {
type: String,
trim: true,
required: true
},
courseId: {
type: String,
ref: 'Course',
default: shortid.generate
}
},
{ timestamps: true }
)
UserSchema.post('save', async function (doc, next) {
if (doc) {
await Course.create({ userId: doc._id })
next()
}
})
const User = mongoose.model('User', UserSchema, 'User')
async function registerAccount() {
const userData = new User({ fullName: 'john doe' })
await userData.save()
console.log('register successfuly')
process.exit(0)
}
registerAccount()
async function buyCourse() {
const user = await User.findOne({ fullName: 'john doe' })
const course = await Course.updateOne(
{ userId: user._id },
{
$push: {
course: {
$each: [
{ name: 'react for beginner', price: 95000 },
{ name: 'vue for beginner', price: 85000 },
{ name: 'angular for beginner', price: 75000 }
]
}
}
}
)
console.log('sucessfuly to buy course')
process.exit(0)
}
async function resultsCourse() {
const user = await User.findOne({ fullName: 'john doe' })
const courseResult = await Course.findOne({ userId: user._id })
.populate({
path: 'userId',
select: 'course firstName lastName'
})
.lean()
console.log({
fullname: user.fullName,
courses: courseResult.course
})
process.exit(0)
}
Example 6: mongoose reference another model
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var eventSchema = Schema({
title : String,
location : String,
startDate : Date,
endDate : Date
});
var personSchema = Schema({
firstname: String,
lastname: String,
email: String,
gender: {type: String, enum: ["Male", "Female"]}
dob: Date,
city: String,
interests: [interestsSchema],
eventsAttended: [{ type: Schema.Types.ObjectId, ref: 'Event' }]
});
var Event = mongoose.model('Event', eventSchema);
var Person = mongoose.model('Person', personSchema);