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/15bd13dc0145148235f6c1686032c52b to your computer and use it in GitHub Desktop.
Save hieunguyendut/15bd13dc0145148235f6c1686032c52b to your computer and use it in GitHub Desktop.
const express = require('express');
const mongoose = require('mongoose');
const autoIncrement = require('mongoose-auto-increment');
const app = express();
mongoose.connect('mongodb://localhost/test');
var Schema = mongoose.Schema;
var personSchema = Schema({
name: String,
age: Number
});
var storySchema = Schema({
title: String,
author: Number
});
storySchema.plugin(autoIncrement.plugin, 'Story');
personSchema.plugin(autoIncrement.plugin, 'Person');
var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);
var author = new Person({
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'}, function(err, story) {
if(err) return console.log(err);
Person.findOne({_id: story._id}, function(err, person) {
if(err) return console.log(err);
person.stories = story
res.json();
});
});
});
app.listen(3001, ()=> console.log('server listen at 3001'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment