Skip to content

Instantly share code, notes, and snippets.

@crguezl
Last active May 2, 2016 22:52
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 crguezl/06cef7cb8078a78a84bc0a28b8e014f8 to your computer and use it in GitHub Desktop.
Save crguezl/06cef7cb8078a78a84bc0a28b8e014f8 to your computer and use it in GitHub Desktop.
/* Mongoose can also populate from multiple collections at the same time. */
"use strict";
const util = require('util');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tutu');
const Schema = mongoose.Schema;
var userSchema = new Schema({
name: String,
connections: [{
kind: String,
item: { type: Schema.Types.ObjectId, refPath: 'connections.kind' }
}]
});
var organizationSchema = new Schema({ name: String, kind: String });
var User = mongoose.model('User', userSchema);
var Organization = mongoose.model('Organization', organizationSchema);
Organization.remove({}).then(()=>{
User.remove({}).then( () => {
var maria;
let dsi = new Organization({ name: 'DSI', kind: 'subject' });
let juana = new User({ name: 'Juana',
connections: [
{kind: 'User', item: maria},
{kind: 'Organization', item: dsi}
]
});
maria = new User({ name: 'Maria',
connections: [
{kind: 'User', item: juana},
{kind: 'Organization', item: dsi}
]
});
juana.connections[0].item = maria;
let things = [ juana, maria, dsi];
Promise.all(things.map((x)=> x.save())).then( () => {
User.findOne({ name: 'Juana' }).populate('connections').exec((error, doc) => {
if (error) console.log(error);
console.log(doc);
console.log(doc.connections[0]); //.item is a User doc
console.log(doc.connections[1]); //.item is an Organization doc
mongoose.connection.close();
})
});
});
});
(function() {
"use strict";
const util = require('util');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tutu');
const Schema = mongoose.Schema;
const personSchema = Schema({
_id : Number,
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
const storySchema = Schema({
_creator : { type: Number, ref: 'Person' },
title : String,
fans : [{ type: Number, ref: 'Person' }]
});
const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);
Person.remove({}).then(()=>{
Story.remove({}).then( () => {
let aaron = new Person({ _id: 0, name: 'Aaron', age: 100 });
aaron.save(function (err) {
if (err) return console.log(err);
}).then( () => {
let story1 = new Story({
title: "Once upon a timex.",
_creator: aaron._id // assign the _id from the person
});
story1.save(function (err) {
if (err) return console.log(err);
}).then(()=>{
Story
.findOne({ title: 'Once upon a timex.' })
.populate('_creator')
.exec(function (err, story) {
if (err) return console.log(err);
console.log('The creator is %s', story._creator.name);
// prints "The creator is Aaron"
}).then( () => {
mongoose.connection.close();
});
});
});
});
});
})();
(function() {
"use strict";
const util = require('util');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tutu');
const Schema = mongoose.Schema;
const personSchema = Schema({
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
const storySchema = Schema({
_creator : { type: Schema.Types.ObjectId, ref: 'Person' },
title : String,
fans : [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);
Person.remove({}).then(()=>{
Story.remove({}).then( () => {
let aaron = new Person({ name: 'Aaron', age: 100 });
let juana = new Person({ name: 'Juana', age: 11 });
let maria = new Person({ name: 'Maria', age: 8 });
let daniel = new Person({ name: 'Daniel', age: 13 });
let sara = new Person({ name: 'Sara', age: 14 });
let people = [aaron, juana, maria, daniel, sara];
Promise.all(people.map((x)=> x.save())).then( () => {
let story1 = new Story({
title: "Once upon a time.",
_creator: aaron // assign the _id from the person
});
/* no es necesario explictar los _id!!! */
story1.fans.push(aaron, juana, maria, sara);
story1.save(function (err) {
if (err) return console.log(err);
}).then(()=>{
Story
.findOne({ title: 'Once upon a time.' })
.populate({
path: 'fans',
match: { age: { $gte: 9 }},
select: 'name -_id',
options: { limit: 4 }
})
.exec(function (err, story) {
console.log(story);
if (err) return console.log(err);
console.log('The fans of "Once upon ..." are %s', story.fans.map((x)=>x.name));
/* We may find however, if we use the aaron object, we
are unable to get a list of the stories. This is because
no story objects were ever 'pushed' onto aaron.stories.*/
console.log("aaron = ",aaron);
}).then( () => {
Story.findOne({ title: 'Once upon a time.' }, function(error, story) {
if (error) { console.log(error); }
story._creator = juana;
console.log("The new author is "+story._creator.name);
story.save().then( () => {
mongoose.connection.close();
});
})
});
});
});
});
});
})();
(function() {
"use strict";
const util = require('util');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tutu');
const Schema = mongoose.Schema;
const personSchema = Schema({
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
const storySchema = Schema({
_creator : { type: Schema.Types.ObjectId, ref: 'Person' },
title : String,
fans : [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);
Person.remove({}).then(()=>{
Story.remove({}).then( () => {
let aaron = new Person({ name: 'Aaron', age: 100 });
let juana = new Person({ name: 'Juana', age: 11 });
let maria = new Person({ name: 'Maria', age: 8 });
let daniel = new Person({ name: 'Daniel', age: 13 });
let sara = new Person({ name: 'Sara', age: 14 });
let people = [aaron, juana, maria, daniel, sara];
Promise.all(people.map((x)=> x.save())).then( () => {
let story1 = new Story({
title: "Once upon a time.",
_creator: aaron // assign the _id from the person
});
/* no es necesario explictar los _id!!! */
story1.fans.push(aaron, juana, maria, sara);
story1.save(function (err) {
if (err) return console.log(err);
}).then(()=>{
Story
.findOne({ title: 'Once upon a time.' })
.populate({
path: 'fans',
match: { age: { $gte: 9 }},
select: 'name -_id',
options: { limit: 4 }
})
.exec(function (err, story) {
console.log(story);
if (err) return console.log(err);
console.log('The fans of "Once upon ..." are %s', story.fans.map((x)=>x.name));
/* We may find however, if we use the aaron object, we
are unable to get a list of the stories. This is because
no story objects were ever 'pushed' onto aaron.stories.*/
console.log("aaron = ",aaron);
aaron.stories.push(story);
aaron.save().then( ()=>{
console.log("aaron = ",aaron);
});
}).then( () => {
Story.findOne({ title: 'Once upon a time.' }, function(error, story) {
if (error) { console.log(error); }
story._creator = juana;
console.log("The new author is "+story._creator.name);
story.save().then( () => {
mongoose.connection.close();
});
})
});
});
});
});
});
})();
(function() {
"use strict";
const util = require('util');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tutu');
const Schema = mongoose.Schema;
const personSchema = Schema({
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
const storySchema = Schema({
_creator : { type: Schema.Types.ObjectId, ref: 'Person' },
title : String,
fans : [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);
Person.remove({}).then(()=>{
Story.remove({}).then( () => {
let aaron = new Person({ name: 'Aaron', age: 100 });
aaron.save(function (err) {
if (err) return console.log(err);
let story1 = new Story({
title: "Once upon a timex.",
_creator: aaron._id // assign the _id from the person
});
story1.save(function (err) {
if (err) return console.log(err);
// thats it!
}).then(()=>{
Story
.findOne({ title: 'Once upon a timex.' })
.populate('_creator')
.exec(function (err, story) {
if (err) return console.log(err);
console.log('The creator is %s', story._creator.name);
// prints "The creator is Aaron"
}).then( () => {
mongoose.connection.close();
});
});
});
});
});
})();
(function() {
"use strict";
const util = require('util');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tutu');
const Schema = mongoose.Schema;
const personSchema = Schema({
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
const storySchema = Schema({
_creator : { type: Schema.Types.ObjectId, ref: 'Person' },
title : String,
fans : [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);
Person.remove({}).then(()=>{
Story.remove({}).then( () => {
let aaron = new Person({ name: 'Aaron', age: 100 });
let juana = new Person({ name: 'Juana', age: 11 });
let maria = new Person({ name: 'Maria', age: 8 });
let daniel = new Person({ name: 'Daniel', age: 13 });
let sara = new Person({ name: 'Sara', age: 14 });
let people = [aaron, juana, maria, daniel, sara];
Promise.all(people.map((x)=> x.save())).then( () => {
let story1 = new Story({
title: "Once upon a time.",
_creator: aaron // assign the _id from the person
});
/* no es necesario explicitar los _id!!! */
story1.fans.push(aaron, juana, maria, sara);
story1.save(function (err) {
if (err) return console.log(err);
}).then(()=>{
Story
.findOne({ title: 'Once upon a time.' })
.populate({
path: 'fans',
match: { age: { $gte: 9 }},
select: 'name -_id',
options: { limit: 2 }
})
.exec(function (err, story) {
console.log("STORY:\n"+story);
if (err) return console.log(err);
console.log('The fans of "Once upon ... " are %s',
story.fans.map((x)=>x.name));
/* We may find however, if we use the aaron object, we
are unable to get a list of the stories. This is because
no story objects were ever 'pushed' onto aaron.stories.*/
console.log("aaron 1 = ",aaron);
aaron.stories.push(story); // not saved to the database
aaron.save().then(() => {
Person.find({name: 'Aaron'}).populate('stories').exec((err,data) => {
console.log('after pushing the story on Aaron:\n',
util.inspect(data, {depth: null}));
console.log("aaron 2 = ",aaron);
Story.findOne({ title: 'Once upon a time.' }, function(error, story) {
if (error) { console.log(error); }
story._creator = juana;
juana.stories.push(story); // not saved to the database
aaron.stories.pop(); // not saved to the database
console.log("The new author is "+story._creator.name);
let p1 = story.save();
let p2 = juana.save();
let p3 = aaron.save();
Promise.all([p1,p2,3]).then( () => {
mongoose.connection.close();
});
})
});
});
//Story.find({ _creator: aaron._id }) // no need to specify the .id
Story.find({ _creator: aaron })
.exec(function (err, stories) {
if (err) return console.log(err);
console.log('The Aaron stories are an array: ', stories.map((x)=>x.title));
// ... Note that this only works for single refs.
// You currently can't manually populate an array of refs.
//aaron.stories = stories;
//console.log("aaron 3 = ",aaron);
//console.log("aaron = ",util.inspect(aaron, {depth: null}));
})
})
});
});
});
});
})();
(function() {
"use strict";
const util = require('util');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tutu');
const Schema = mongoose.Schema;
const personSchema = Schema({
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
const storySchema = Schema({
_creator : { type: Schema.Types.ObjectId, ref: 'Person' },
title : String,
fans : [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);
Person.remove({}).then(()=>{
Story.remove({}).then( () => {
let aaron = new Person({ name: 'Aaron', age: 100 });
aaron.save(function (err) {
if (err) return console.log(err);
let story1 = new Story({
title: "Once upon a timex.",
_creator: aaron._id // assign the _id from the person
});
story1.save(function (err) {
if (err) return console.log(err);
// thats it!
}).then(()=>{
Story
.findOne({ title: 'Once upon a timex.' })
.populate('_creator')
.exec(function (err, story) {
if (err) return console.log(err);
console.log('The creator is %s', story._creator.name);
// prints "The creator is Aaron"
// See section Updating refs in http://mongoosejs.com/docs/populate.html
var guille = new Person({ name: 'Guillermo' });
guille.save(function (err) {
if (err) return handleError(err);
story._creator = guille;
console.log(story._creator.name);
// prints "Guillermo" in mongoose >= 3.6
// see https://github.com/Automattic/mongoose/wiki/3.6-release-notes
story.save(function (err) {
if (err) return handleError(err);
Story
.findOne({ title: /timex/i })
.populate({ path: '_creator', select: 'name' })
.exec(function (err, story) {
if (err) return handleError(err);
console.log('The creator is %s', story._creator.name)
// prints "The creator is Guillermo"
}).then( () => {
mongoose.connection.close();
});
})
})
})
});
});
});
});
})();
(function() {
"use strict";
const util = require('util');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tutu');
const Schema = mongoose.Schema;
const personSchema = Schema({
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
const storySchema = Schema({
_creator : { type: Schema.Types.ObjectId, ref: 'Person' },
title : String,
fans : [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);
Person.remove({}).then(()=>{
Story.remove({}).then( () => {
let aaron = new Person({ name: 'Aaron', age: 100 });
let juana = new Person({ name: 'Juana', age: 11 });
let maria = new Person({ name: 'Maria', age: 8 });
Promise.all([aaron.save(), juana.save(), maria.save()]).then( () => {
let story1 = new Story({
title: "Once upon a time.",
_creator: aaron._id // assign the _id from the person
});
story1.fans.push(aaron._id, juana._id, maria._id);
story1.save(function (err) {
if (err) return console.log(err);
// thats it!
}).then(()=>{
Story
.findOne({ title: 'Once upon a time.' })
.populate('_creator fans') // space delimited path names
.exec(function (err, story) {
if (err) return console.log(err);
console.log('The creator is %s', story._creator.name);
console.log('The fans are %s', story.fans.map((x) => x.name));
}).then( () => {
Story.findOne({ title: 'Once upon a time.' }, function(error, story) {
if (error) { console.log(error); }
story._creator = juana;
console.log("The new author is "+story._creator.name);
story.save().then( () => {
mongoose.connection.close();
});
})
});
});
});
});
});
})();
(function() {
"use strict";
const util = require('util');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tutu');
const Schema = mongoose.Schema;
const userSchema = Schema({
name : String,
friends : [{ type: Schema.Types.ObjectId, ref: 'User' }]
});
const User = mongoose.model('User', userSchema);
User.remove({}).then(()=>{
let aaron = new User({ name: 'Aaron', friends: [] });
let juana = new User({ name: 'Juana', friends: [ aaron ] });
let daniel = new User({ name: 'Daniel', friends: [ juana, aaron ] });
let sara = new User({ name: 'Sara', friends: [ juana, daniel ] });
juana.friends.push(daniel, sara);
let people = [aaron, juana, daniel, sara];
Promise.all(people.map((x)=> x.save())).then( () => {});
User.findOne({ name: 'Sara' }).populate({
path: 'friends',
// Get friends of friends - populate the 'friends' array for every friend
populate: { path: 'friends' }
}).exec(function (err, user) {
console.log(util.inspect(user, { depth: null}));
console.log(`friends of ${user.name} are
${user.friends.map((x)=> x.name)}`);
console.log(`friends of ${user.friends[0].name} are
${user.friends[0].friends.map((x)=> x.name)}`);
}) /* exec */
.then(()=>{
mongoose.connection.close();
})
}) /* remove */;
})();
"use strict";
const util = require('util');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;
var eventSchema = new Schema({
name: String,
// The id of the corresponding conversation
// Notice there's no ref here!
conversation: ObjectId
});
var conversationSchema = new Schema({
numMessages: Number
});
var db1 = mongoose.createConnection('localhost:27000/db1');
var db2 = mongoose.createConnection('localhost:27001/db2');
var Event = db1.model('Event', eventSchema);
var Conversation = db2.model('Conversation', conversationSchema);
Conversation.remove({}).then(()=>{
Event.remove({}).then( () => {
let red = new Conversation({numMessages: 11});
let green = new Conversation({numMessages: 14});
let yellow = new Conversation({numMessages: 34});
let conversations = [red, green, yellow];
let aaron = new Event({ name: 'Aaron', conversation: red });
let juana = new Event({ name: 'Juana', conversation: green });
let maria = new Event({ name: 'Maria', conversation: red });
let daniel = new Event({ name: 'Daniel', conversation: yellow });
let sara = new Event({ name: 'Sara', conversation: yellow });
let people = [aaron, juana, maria, daniel, sara];
let p1 = Promise.all(conversations.map((x)=> x.save()));
let p2 = Promise.all(people.map((x)=> x.save()));
Promise.all([p1, p2]).then( () => {
Event.
find({}).
populate({ path: 'conversation', model: Conversation }).
exec(function(error, docs) {
console.log(docs);
mongoose.disconnect();
});
})
})
})
# tasks for populateacrossdatabases.js
desc "mongod on 27000"
task :mongo2 do
sh "mongod --port 27000 --dbpath /tmp/m2"
end
desc "mongod on 27001"
task :mongo1 do
sh "mongod --port 27001 --dbpath /tmp/m1"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment