I want to set a boolean flag on a collection containing an array. As an example of data:
{
_id: "12341234",
name: {
first: 'Jeff',
last: 'Jefferson'
},
emails: [{
address: 'fake#fake.org',
verified: true,
primary: true
}, {
address: 'fake#fake.net',
verified: true,
primary: false
}]
}
On every entry in this table, I want the array of emails to only ever have a single entry that is primary: true.
With keys in a table, you can do something like as follows to ensure uniqueness:
Meteor._ensureIndex({ 'name.last': 1 }, { unique: 1 });
Would there be a way to do this on an array in a single entry?
Look at adding custom validation with aldeed:simple-schema, attached to your collection with aldeed:collections2
customUsers = new Mongo.Collection('customUsers');
customUsers.attachSchema(new SimpleSchema({
name: {
type: new SimpleSchema({
first: { type: String},
last: { type: String},
}),
},
emails: {
type: Array,
custom: function() {
if (_.compact(_.pluck(this.value, 'primary')).length !== 1) {
return 'NotOnePrimaryEmail';
}
},
},
'emails.$': {
type: Object,
},
'emails.$.address': {
type: String,
regEx: SimpleSchema.RegEx.Email,
},
'emails.$.verified': {
type: Boolean,
},
'emails.$.primary': {
type: Boolean,
},
}));
SimpleSchema.messages({
NotOnePrimaryEmail: 'You must have one, and only one, email marked as primary',
});
if (Meteor.isServer) {
Meteor.startup(function() {
objValid = {
name: {
first: 'Jeff',
last: 'Jefferson',
},
emails: [{
address: 'fake#fake.org',
verified: true,
primary: true,
}, {
address: 'fake#fake.net',
verified: true,
primary: false,
},],
};
objNoPrimary = {
name: {
first: 'Jeff',
last: 'Jefferson',
},
emails: [{
address: 'fake#fake.org',
verified: true,
primary: false,
}, {
address: 'fake#fake.net',
verified: true,
primary: false,
},],
};
objMultiplePrimary = {
name: {
first: 'Jeff',
last: 'Jefferson',
},
emails: [{
address: 'fake#fake.org',
verified: true,
primary: true,
}, {
address: 'fake#fake.net',
verified: true,
primary: true,
},],
};
[objValid, objNoPrimary, objMultiplePrimary].forEach(
function(obj) {
try {
customUsers.insert(obj);
console.log('Object was valid, inserted into collection');
} catch (err) {
console.log('Error: ' + err.sanitizedError.reason);
}
}
);
});
}
Output from server console:
~/test/schema$ meteor
[[[[[ ~/test/schema ]]]]]
=> Started proxy.
=> Started MongoDB.
=> Started your app.
=> App running at: http://localhost:3000/
I20151008-15:04:15.280(13)? Object was valid, inserted into collection
I20151008-15:04:15.281(13)? Error: You must have one, and only one, email marked as primary
I20151008-15:04:15.281(13)? Error: You must have one, and only one, email marked as primary
Related
I get no results, and I don't know why. (DB has documents with this owner id)
As you can see, I've tried using Types.ObjectId but no success yet.
export const getStores = async (
{ owner, platform }: {
owner: string
platform?: string
}): Promise<StoreMainInfo[]> => {
console.log('owner', owner); // owner 62210e86f36af71f58022971
const stores = await StoreModel.aggregate([
{
'$project': {
'_id': 1,
'platform': 1,
'name': 1,
'category': 1,
'logo': 1,
'urls': 1,
'stats': 1,
}
}, {
$match: { owner: Types.ObjectId(owner) }
},
]);
if (!stores.length) {
throw ApiError.BadRequest('Stores not found.');
}
return stores;
};
// Model:
const StoreSchema: Schema = new Schema({
owner: { type: Types.ObjectId, ref: CollectionNames.user, required: true },
platform: { type: String, required: true },
name: { type: String, required: true },
category: { type: String, required: false },
logo: { type: LogoSchema, required: false },
urls: { type: UrlsSchema, required: true },
stats: { type: StatsSchema, required: true },
suppliers: { type: [SupplierSchema], required: true },
})
export default model<Document & Store>(CollectionNames.store, StoreSchema)
I need help with mongo, I need to make a query resulting in a objext and many object nested resulting of a one to many relation ship of these schemas:
const ProductSchema = new Schema({
name: { type: String, required: true, unique:true },
picture: { type: String },
description: { type: String, required: true },
isEnabled: { type: Boolean, required: true },
brand: { type: Schema.Types.ObjectId, ref:'Brand' },
slug: { type: String, required: true },
category: { type: mongoose.Schema.Types.ObjectId, ref:'Category' },
reviews: [{ type: mongoose.Schema.Types.ObjectId, ref:'Review' }]
const PackageSchema = new Schema({
type: { type: String, enum:["WEIGHT", "EACH"], required: true },
value: { type: Number, required: true },
price: { type: Number, required: true },
stock: { type: Boolean, required: true},
description: { type: String, required: true},
product: { type: mongoose.Schema.Types.ObjectId, ref:'Product', required: true },
dispensary: { type: mongoose.Schema.Types.ObjectId, ref:'Dispensary', required: true }
This is the code i made
const dispensaryID;
payload = _thisModel.aggregate([
{
$lookup:{
from: "packages",
localField:'_id',
foreignField:'product',
as:"package"
}
},
{"$unwind": {path:"$package", preserveNullAndEmptyArrays: true}} ,
{
$group:
{
_id:"$_id",
number: {
$sum: "$package"
},
package: {$push: '$package'},
}
},
],(aggErr, aggResult) => {
(aggErr) ? console.log(aggResult)
: console.log(aggResult)
})
Buy it is resulting on this:
{ _id: 5ebf98724ef6e503ccd7ae4f, clicks: 0, package: [ [Object] ] },
{
_id: 5ebf98614ef6e503ccd7ae4e,
clicks: 0,
package: [ [Object], [Object], [Object], [Object] ]
},
{ _id: 5ebed37b52ec0043fca22893, clicks: 0, package: [] }
So i need to unbind those objects, I need to see the packages details instead some "[Object]", I tried reconfiguring the script but this is the nearest result I got, also I need to check if a dispensary: { type: mongoose.Schema.Types.ObjectId, ref:'Dispensary', required: true } given in the second schema exists in any of those packages, I will give a const to check if it maches, and add a prop says exists: true on the product object or only delete the whole product object with the packages.
Thanks for the help
I have 2 Models, User and Post. I want to be able to get User information when querying a post, and be able to get all of a User's posts when querying a user.
they have an association as follows:
User.hasMany(Post, {
foreignKey: 'user',
as: 'posts'
});
Post.belongsTo(User, {
foreignKey: 'id',
sourceKey: 'user',
as: 'userObject'
})
Post.addScope('defaultScope', {
include: [{ model: User, as: 'userObject' }],
}, { override: true })
User.addScope('defaultScope', {
include: [{ model: Post, as: 'posts' }],
}, { override: true })
Here are my Models
User.js
module.exports.userType = new GQL.GraphQLObjectType({
name: 'User',
fields: () => {
const { postType } = require('../Post/Post');
return {
id: {
type: new GQL.GraphQLNonNull(GQL.GraphQLString),
description: 'user unique id'
},
ci_username: {
type: new GQL.GraphQLNonNull(GQL.GraphQLString),
unique: true,
description: 'case INSENSITIVE username of the user'
},
username: {
type: new GQL.GraphQLNonNull(GQL.GraphQLString),
description: 'case SENSITIVE username of the user'
},
password: {
type: new GQL.GraphQLNonNull(GQL.GraphQLString),
description: 'password for the user'
},
first_name: {
type: new GQL.GraphQLNonNull(GQL.GraphQLString),
description: 'first name of user'
},
last_name: {
type: GQL.GraphQLString,
description: 'last name of user (optional)'
},
profile_picture: {
type: GQL.GraphQLString,
description: 'profile picture for the user'
},
posts: {
type: GQL.GraphQLList(postType),
description: 'list of users posts'
}
}
},
})
/** define User model for the database */
module.exports.User = db.define('user', {
id: {
type: Sequelize.UUID,
primaryKey: true,
unique: true,
},
ci_username: {
type: Sequelize.STRING,
unique: true,
},
username: Sequelize.STRING,
password: Sequelize.STRING,
first_name: Sequelize.STRING,
last_name: Sequelize.STRING,
profile_picture: Sequelize.STRING,
}, {
// Tells sequelize not to query the "CreatedAt" or "UpdatedAt" Columns
timestamps: false
})
Post.js
module.exports.postType = new GQL.GraphQLObjectType({
name: 'Post',
fields: () => {
const { userType } = require('../User/User');
return {
id: {
type: new GQL.GraphQLNonNull(GQL.GraphQLString),
description: 'post unique id'
},
name: {
type: new GQL.GraphQLNonNull(GQL.GraphQLString),
description: 'name of the post'
},
user: {
type: userType,
description: 'user object of who created the post'
},
created_at: {
type: new GQL.GraphQLNonNull(GQL.GraphQLString),
description: 'the datetime the post was created',
}
}
},
})
/** define User model for the database */
module.exports.Post = db.define('post', {
id: {
type: DataTypes.UUID,
primaryKey: true,
unique: true,
},
name: DataTypes.STRING,
user: {
type: DataTypes.STRING,
references: {
model: 'users',
key: 'id'
}
},
created_at: {
type: DataTypes.TIME,
defaultValue: DataTypes.NOW
}
}, {
// Tells sequelize not to query the "CreatedAt" or "UpdatedAt" Columns
timestamps: false
})
Here are my Queries:
allUsers.js
const allUsers = {
type: new GQL.GraphQLList(userType),
args: {
username: {
description: 'username of the user',
type: GQL.GraphQLString,
},
// An arg with the key limit will automatically be converted to a limit on the target
limit: {
type: GQL.GraphQLInt,
default: 10
},
// An arg with the key order will automatically be converted to a order on the target
order: {
type: GQL.GraphQLString
}
},
// use graphql-sequelize resolver with the User model from database
resolve: resolver(User)
}
allPosts.js
const allPosts = {
type: new GQL.GraphQLList(postType),
args: {
username: {
description: 'username of the user',
type: GQL.GraphQLString,
},
// An arg with the key limit will automatically be converted to a limit on the target
limit: {
type: GQL.GraphQLInt,
default: 10
},
// An arg with the key order will automatically be converted to a order on the target
order: {
type: GQL.GraphQLString
}
},
// use graphql-sequelize resolver with the Post model from database
resolve: resolver(Post)
}
I'm currently getting a Maximum call stack size exceeded. I assume because the resolver in the queries are recursively getting details on posts and users infinitely.
Does anyone know of any way to put a depth limitation on the resolver? Or is it just not possible to have a recursive query like this?
You would have to remove the default scope from the included model as shown here like this:
Post.addScope('defaultScope', {
include: [{ model: User.scope(null), as: 'userObject' }],
}, { override: true })
User.addScope('defaultScope', {
include: [{ model: Post.scope(null), as: 'posts' }],
}, { override: true })
To support additional depth, you'd need to implement resolvers for the fields in question, for example:
function resolve (user) {
if (user.posts) {
return user.posts
}
return user.getPosts()
}
I have a mongoose document that has timestamps option enabled. I want to make decisions based on this timestamps but I noticed something weird according to my understanding.
I tried to get those values the traditional way (document.createdAt) but that returns undefined. But if I use document.get('createdAt') the value comes as in the database. The docs don't say anything about this. My question is: ¿Why timestamps behave this way?
Edit
The schema I'm using has an array of embedded schemas:
const Customer = new mongoose.Schema({
roles: {
type: [{
type: String,
enum: 'app b2b iot'.split(' '),
}],
default: 'app',
set: (value = []) => (value.includes('app')
? value
: value.concat('app')),
},
email: {
address: {
type: String,
trim: true,
lowercase: true,
set(email) {
this._previousEmail = this.email.address
return email
},
},
verified: {
type: Boolean,
},
token: String,
},
nickname: {
type: String,
trim: true,
},
recoveryToken: String,
gender: String,
birthday: String,
lastLogin: Date,
isAnonymous: {
type: Boolean,
default: false,
},
devices: [Device],
});
Device schema:
const Device = new mongoose.Schema({
customer: {
type: ObjectId,
ref: 'Customer',
required: true,
},
handle: {
type: String,
},
platform: {
type: String,
required: true,
set: toLowerCase,
},
info: Mixed,
smartFilterTags: [{
type: String,
}],
paidUntil: Date,
nh: {
tier: String,
_id: {
type: ObjectId,
},
location: {
type: {
type: String,
enum: ['Point'],
default: 'Point',
},
coordinates: [{
type: Number,
}],
},
})
I have a base plugin that apply when I compile models:
function basePlugin(schema) {
schema.add({
archivedAt: Date,
})
schema.set('timestamps', true)
schema.set('toJSON', {
virtuals: true,
})
schema.set('toObject', {
virtuals: true,
})
}
I am having trouble with performing operations during the pre('validate') hook. I need to do some prevalidation (making sure at least one of 2 different fields is populated, but not necessarily both, for example).
const AccessorySchema = new Schema({
accessory: {
type: String,
required: true,
},
category: {
type: String,
required: true,
enum: [
'Offense',
'Defence',
'Miscellaneous'
]
},
space: {
type: Number,
required: true,
validate: {
validator: Number.isInteger,
message: 'Space must be an integer'
}
},
priceFixed: {
type: Number,
required: false,
validate: {
validator: Number.isInteger,
message: 'Fixed Price must be an integer'
}
},
priceMultiplier: {
type: [Schema.Types.Mixed],
required: false
},
weightFixed: {
type: Number,
required: false,
validate: {
validator: Number.isInteger,
message: 'Fixed Weight must be an integer'
}
},
weightMultiplier: {
type: [Schema.Types.Mixed],
required: false
},
vehicles: {
type: [String],
required: true,
enum: ["car","cycle"]
}
});
AccessorySchema.pre('validate', (next) => {
console.log(this);
next();
});
And I send it this object :
{
accessory: "some name",
category: "Miscellaneous",
priceMultiplier: [3,5],
weightMultiplier: [3,5],
space: 0,
vehicles: ["car"]
}
this logs {} and populates the mongo DB. But I can't check any of the properties in pre validation.
mongoose version is ^4.7.7, nodejs 6.10.2, mongodb version is 3.2.9
How can I access the data in the pre validation hook?
do not use arrow function, it doesn't bind the context.
Change your code to below
AccessorySchema.pre('validate', function(next){
console.log(this);
next();
});