Created
December 28, 2017 00:37
-
-
Save hieunguyendut/29cae069be8fb630c8ecf9c6fd8a008b 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
var Mongoose = require('mongoose'); | |
var autoIncrement = require('mongoose-auto-increment') | |
var Schema = Mongoose.Schema; | |
// Mongoose.Promise = require('bluebird'); | |
var db = Mongoose.connect('mongodb://localhost/Population', { | |
useMongoClient: true | |
}, (err) => { | |
if (err) { | |
console.log(`Can't connect to MongoDB`); | |
} else { | |
console.log(`Connect to MongoDb sucess`); | |
} | |
}); | |
autoIncrement.initialize(db); | |
var personSchema = Schema({ | |
name: String, | |
age: Number, | |
_id: {type: Number, ref: 'Story'} | |
}); | |
var descriptionSchema = Schema({ | |
content: String, | |
_id: {type: Number, red: 'Story'} | |
}); | |
var storySchema = Schema({ | |
test: Number, | |
descriptionId: {type: Number, ref: 'Description'}, | |
personId: {type: Number, ref: 'Person'}, | |
title: String | |
}); | |
personSchema.plugin(autoIncrement.plugin, 'Person'); | |
storySchema.plugin(autoIncrement.plugin, 'Story'); | |
descriptionSchema.plugin(autoIncrement.plugin, 'Description'); | |
var Story = Mongoose.model('Story', storySchema); | |
var Person = Mongoose.model('Person', personSchema); | |
var Description = Mongoose.model('Description', descriptionSchema); | |
var author = new Person({ | |
name: 'Ian Fleming', | |
age: 50 | |
}); | |
author.save(function (err) { | |
if (err) return console.log(err); | |
description = new Description({ | |
content: 'I hope this can be help me go sleep soon.' | |
}); | |
description.save(function(err){ | |
if (err) { | |
return console.log("Loi khi save story"); | |
} | |
}); | |
var story1 = new Story({ | |
personId: author._id, | |
test: 1, | |
descriptionId: description._id, | |
title: 'Casino Royale' | |
}); | |
console.log(story1); | |
story1.save(function (err) { | |
if (err) { | |
return console.log("Loi khi save story"); | |
} | |
// thats it! | |
}); | |
}); | |
Story. | |
findOne({ title: `Casino Royale` }). | |
populate('personId'). // only return the Persons name | |
populate('descriptionId'). | |
exec(function (err, story) { | |
if (err) return handleError(err); | |
console.log(story); | |
// console.log('The author is %s', story.author.name); | |
// // prints "The author is Ian Fleming" | |
// console.log('The authors age is %s', story.author.age); | |
// prints "The authors age is null' | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment