Created
December 28, 2017 12:27
-
-
Save hieunguyendut/94fb6e2a4aa1b4bb6e8fa7362a0efd9f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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