is there any kind of trigger at mongoose model level which provide the capability to set the value of the open field = false when the number of the members collection reaches 100?
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var listSchema = new Schema({
name: {
type: String,
required: true,
trim: true
},
desc: {
type: String
},
open: {
type: Boolean,
default: true
},
members: [{
userid: {
type: Schema.Types.ObjectId, ref: 'User'
},
prId: {
type: Schema.Types.ObjectId, ref: 'PR'
},
checkedIn: {
type: Boolean
}
}]
});
module.exports = mongoose.model('List', listSchema);
Triggers are not available in mongo. It's hard to say why you want to change documents when collection reaches some limit by maybe capped collection is what you really want?
new Schema({..}, { capped: { size: 1024, max: 100 } });
size is maximum collection size in bytes and max is maximum number of documents that can be inserted in collection.
Related
I'm using mongoose to connect to MongoDB and I have a doubt about how can I make a query between two related collections
I have these Schemas.
const users = new mongoose.Schema({
name: String,
lastname: String,
age: Number,
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comments',
}
],
}, { timestamp: true, strict: false });
const comments = new mongoose.Schema({
message: {
type: String,
},
description: {
type: String,
},
candidates: Number,
}, { timestamp: true, strict: false });
well, the idea is get all users that contains comments with candidates value > 100
Is this possible to do just one query that will return the users that have comments with that condition?
TIA !
I am attempting to set a capped parameter to my collection within my mongoose.Schema that did not include capped at first.
Any help welcome.
My Schema:
const mongoose = require('mongoose')
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: { type: String, required: true },
email: { type: String },
password: { type: String },
isAdmin: {type: Boolean, default: false},
avatar: { type: String },
joinDate: { type: Date, default: Date.now() },
},{ autoCreate: true, capped : 1024})
userSchema.set('timestamps', true);
const Users = mongoose.model('Users', userSchema)
module.exports = Users;
I get following error:
Error: A non-capped collection exists with the name: users
To use this collection as a capped collection, please first convert it.
Seems like you have already created a users collection in your database. So to convert it into a capped run below command either in mongoshell or robomongo
db.runCommand( { convertToCapped: 'users', size: 1024 } )
I have a field in my mongoose schema called "active" and I wanted to know if there is any way that every date expired in a particular document, then the "active" field would change to false. how should I do that if so, What is the easiest way to do this? else, what is recommended?
And below is my Schema;
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema({
user_id: {
type: String,
required: true
},
firstName: {
type: String,
required: true
},
username: {
type: String,
required: true
},
email: {
type: String,
required: true
},
hash: {
type: String,
required: true
},
active: {
type: Boolean,
},
role: {
type: String,
required: true
},
createdDate: {
type: Date,
default: Date.now
}
});
schema.set('toJSON', { virtuals: true });
module.exports = mongoose.model('User', schema);
You can do this with a feature in mongo called Change Streams that allow you to access real-time data changes. You can subscribe to the changes of a single collection or the whole database and react to them. You can also filter for specific changes or transforms. For your case an example would be something like this.
EDIT: Change streams implementation is only available on replica sets.
const pipeline = [
{ $match: { expire_date: {$lt: Date.now()} } },
{ $set: { active: false } }
];
const collection = db.collection('user');
const changeStream = collection.watch(pipeline);
changeStream.on('change', next => {
// process next document
});
I have two schemas and from each, I want to return a single property.
Here is the schema for a single document or file.
// #ts-check
import { Schema, model } from "mongoose";
const docSchema = new Schema({
name: { type: String, required: true },
approved: { type: Boolean, default: false },
docType: { type: String, required: true },
size: { type: Number, required: true },
bucket: { type: Schema.Types.ObjectId, ref: "Bucket" }
});
docSchema.methods.getSize = function(cb) {
// Return the size of document
};
const Doc = model("Document", docSchema);
export default Doc;
And this is the schema for a bucket of documents
// #ts-check
import { Mongoose, Schema, model } from "mongoose";
const bucketSchema = new Schema({
name: { type: String, required: true, index: true, unique: true },
projectId: { type: String, required: true, index: true },
contractorId: { type: String, required: true, index: true },
Docs: [{ type: Schema.Types.ObjectId, ref: "Document" }]
});
bucketSchema.methods.getSize = function(cb) {
// return the size of all documents that belong to a single bucket
// How do I traverse over the Docs array and use Doc.getSize()???
};
const Bucket = model("Bucket", bucketSchema);
export default Bucket;
Is there a way to do this? I don't want to have to query the database each time I need to get the size of the bucket and then traverse over the results and add the size of each document. I want to make it simple so that basically I call Bucket.getSize() and it returns me the size of the bucket so I can restrict the users from uploading files when they've exceeded a certain limit.
Any help would be appreciated.
I'm trying to fetch some documents from my db. In each document, there is a field called 'owner' which is an ObjectId of a user. I want to fetch all of the documents of a specific user. I have the user id and when I'm trying to do something like this:
exports.getBoxes = function(req, res) {
const { user } = res.locals;
const query = db.Box.find();
query.where('owner').equals(user._id);
query.exec(function(err, boxes) {
console.log(boxes);
});
}
I get an empty array. I saw in my db and there are many boxes that corresponds to this query. What's wrong with it?
UPDATE
Here is my schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const timestamps = require('mongoose-timestamps');
const BoxSchema = new Schema({
description: {
type: String,
trim: true
},
producer: {
type: String,
trim: true
},
cycle: {
type: String,
trim: true
},
owner: {
type: Schema.ObjectId,
ref: 'Supplier'
},
event: {
type: Schema.ObjectId,
ref: 'Event'
},
type: {
type: String,
enum: []
},
creditTerms: {
type: String,
enum: ['Cash', '30 Days', '60 Days', '90 Days', '120 Days']
},
bids: [{
type: Schema.ObjectId,
ref: 'Bid'
}],
looking: [{
type: Schema.ObjectId,
ref: 'User'
}],
sold: Boolean,
paid: Boolean,
delivered: Boolean,
sealed: Boolean,
initialPrice: Number,
value: Number,
cts: Number,
ppc: Number,
finalPrice: Number
});
BoxSchema.plugin(timestamps);
module.exports = mongoose.model('Box', BoxSchema);
And here is an example of documents that I try to fetch:
https://i.gyazo.com/38f2d16d6831b831adb3cc448ef74d01.png
Okay guys I managed to solve this problem. The problem was that the owner field in the box schema referenced a Supplier object, not a User object. So I solved it like so:
const { user } = res.locals;
return db.Supplier.findOne({ userId: user._id })
.populate('boxes').exec(function(err, supplier) {
if(err || !supplier) return res.sendStatus(404);
res.json(supplier.boxes);
});