How to do it...

Let's follow these steps to add an objectId reference relationship between users and posts:

  1. First, let's create a /routes/api/users.js route configuration for working with users. We will also configure its JSON API serialization configuration, including a reference post that will just contain a list of IDs to blog posts written by this user:
var express = require('express');
var router = express.Router();
var restFactory = require('../../middleware/rest');
var Users = require('../../models/users');

var serialize = {
transform: function(post) {
return post.toObject();
},
id: '_id',
attributes: ['firstName', 'lastName', 'email', 'role', 'posts'],
posts: {
ref: true
}
};

var deserialize = {
keyForAttribute: 'dash-case'
};

module.exports = restFactory('users', Users, serialize, deserialize);
  1. We will need to include and add our users route to our /routes/api.js route configuration as well:
...
var users = require('./api/users');

...
router.use('/customers', jwt.active(), stripe.getCustomers);
router.use('/images', jwt.active(), jwt.require('role', '===', 'admin'), images);
router.use('/posts', jwt.active(), jwt.require('role', '===', 'admin'), posts);
router.use('/users', jwt.active(), jwt.require('role', '===', 'admin'), users);

...
  1. To make working with multiple document models that have relationships more straightforward, we will extract our /database.js mocks to its own /mocks.js configuration. This will make maintaining and configuring our mocks more easy in our application:
var faker = require('faker');
var Post = require('./models/posts');
var User = require('./models/users');

var makePost = function() {
var markdown = faker.lorem.sentences();
markdown += "## " + faker.lorem.sentence() + " ";
markdown += "[" + faker.lorem.words() + "](" + faker.internet.url() + ") ";

return new Post({
title: faker.lorem.words(),
content: markdown,
published: faker.date.past(),
});
};

var makeUser = function() {
return new User({
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
email: faker.internet.email(),
password: faker.internet.password(),
role: 'author'
});
};

module.exports = {
generateAuthorAndPosts: function(postCount) {
var user = makeUser();

let posts = [];
for (var i=0; i < postCount; i++) {
var post = makePost();
post.author = user;
posts.push(post);
}

user.posts = posts;
user.save().then(function(user) {
console.log('created new author: ' + user.email);
return Post.insertMany(posts).then(function() {
console.log('created ' + postCount + ' new posts');
}).catch(function(error) {
throw error;
});
}).catch(function(error) {
throw error;
});
},

generateAdmin: function() {
var admin = new User({
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
email: '[email protected]',
password: 'Secret',
role: 'admin'
});

return admin.save().then(function(user) {
console.log("created new admin: " + user.email);
}).catch(function(error) {
throw error;
});
}
};
  1. In our /database.js configuration, we will simply include our new /mocks.js configuration and use it to set up new authors and posts, as well as our admin account:
var env = process.env.NODE_ENV || 'development';
var mongoose = require('mongoose');
mongoose.Promise = require("bluebird");
mongoose.connect('mongodb://localhost/mean-db').then(function() {
if (env == 'development') {
var mocks = require('./mocks');
mongoose.connection.db.dropDatabase().then(function() {

mocks.generateAuthorAndPosts(3);
mocks.generateAuthorAndPosts(3);
mocks.generateAuthorAndPosts(3);
mocks.generateAdmin()

});
}

}, function(error) {
console.error('failed to connect to MongoDB...', error);
});

module.exports = mongoose.connection;
  1. Finally, in our /models/users.js model configuration, we will add our new posts property that will be mapped as a placeholder for an array of ObjectId references for our posts model:
...
var userSchema = new Schema({
firstName: String,
lastName: String,
email: { type: String, unique: true, required: true },
password: { type: String, required: true },
role: String,
posts: [{ type: Schema.Types.ObjectId, ref: 'posts' }]
});
...
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.76.135