Skip to content

Instantly share code, notes, and snippets.

@hieunguyendut
Created December 28, 2017 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hieunguyendut/94fb6e2a4aa1b4bb6e8fa7362a0efd9f to your computer and use it in GitHub Desktop.
Save hieunguyendut/94fb6e2a4aa1b4bb6e8fa7362a0efd9f to your computer and use it in GitHub Desktop.
const express = require('express');
const mongoose = require('mongoose');
const app = express();
mongoose.connect('mongodb://localhost/test');
var Schema = mongoose.Schema;
var personSchema = Schema({
_id: Schema.Types.ObjectId,
name: String,
age: Number,
stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
author: { type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);
var author = new Person({
_id: new mongoose.Types.ObjectId(),
name: 'Ian Fleming',
age: 50
});
author.save(function (err) {
if (err) return handleError(err);
var story1 = new Story({
title: 'Casino Royale',
author: author._id // assign the _id from the person
});
story1.save(function (err) {
if (err) return handleError(err);
// thats it!
});
});
app.get('./', function(req, res) {
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);
// prints "The author is Ian Fleming"
res.json({name: story.author.name});
});
});
app.listen(3000, ()=> console.log('server listen at 3000'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment