mango template to receive the callback after auto expire of document - mongodb

I have a collection like below, which has expire-time set like below as part of schema .
db.createCollection(
"userDetails",
{
capped: false,
validator: {
$jsonSchema: {
bsonType: "object",
required: ["userId","userName"],
properties: {
userId: {
bsonType: "string",
description: "must be a string and is required"
},
userName: {
bsonType: "string",
description: "must be a string and match the regular expression pattern"
},
}
}
},
validationLevel: "strict",
validationAction: "error"
}
);
db.userDetails.createIndex( { "userName": 1 }, { expireAfterSeconds:6000});
So now whenever it expires it is getting delete from the mongodb, but I have some other requirement where I have to notify some other service about this deletion so I tried below code but this will I have execute every time, also I am not getting any records.
template.execute("userDetails", new CollectionCallbackBoolean>() {
public Boolean doInCollection(userDetails.class, DBCollection collection) throws MongoException, DataAccessException {
List<Document> indexes = collection.getIndexInfo();
for (Document document : indexes) {
log.info("Docouments " + document.get("userName"))
}
}
return false;
}
});
So how to register to mongo for a callback to get these expired records using mongotemplate..

Related

Trying ti edit a document via MongoDB Compass. What should I type for a key that has data type "bson date"?

Doc looks like this (simplified)
{
"_id": {
"$oid": "62112eed1ccb3f211c1b7116"
},
"joinDate": 1412180887
}
Validation schema
{
$jsonSchema: {
bsonType: 'object',
required: [ 'joinDate' ],
properties: {
joinDate: {
bsonType: 'date'
}
}
}
}
Not sure what I should type when I edit the field joinDate manually
the above value (integer) fails

GraphQL nested document returns null on mutation

I am using MongoDB with Mongoose and GraphQL for a class project. I am stuck on an issue with GraphQL returning null on fields within a nested document reference (postedBy which references the User schema). I expect the fields to be populated by the referenced object data, but only the ID returns.
Model
const postSchema = new Schema(
{
postText: {
type: String,
required: 'You need add text to your post',
minlength: 1,
maxlength: 10000,
},
createdAt:{
type: Date,
default: Date.now,
get: createdAtVal => dateFormat(createdAtVal)
},
postedBy: {
type: Schema.Types.ObjectId, ref: "User",
required: true
},
comments: [commentSchema]
},
{
toJSON: {
virtuals: true,
getters: true
},
}
)
postSchema.virtual('commentCount').get(function() {
return this.comments.length;
});
const Post = model('Post', postSchema);
module.exports = Post;
TypeDef
type Post {
_id: ID
postText: String
createdAt: String
postedBy: User
comments: [Comment]
commentCount: Int
}
Resolver
addPost: async (parent, args, context) => {
if (context.user) {
const post = await Post.create({ ...args, postedBy: context.user._id });
await User.findByIdAndUpdate(
{ _id: context.user._id },
{ $push: { posts: post._id } },
{ new: true }
);
return post;
}
throw new AuthenticationError('You need to be logged in!');
}
I am able to successfully query the post and have the referenced field populated with the user's _id, username, and image(url). When I run the mutation, the username and image return null.
Here is my mutation:
mutation addPost($PostText: String!) {
addPost(postText: $postText) {
_id
postText
createdAt
postedBy {
_id
username
image
}
commentCount
comments {
_id
}
}
}
And here is the response it gets:
{
"data": {
"addPost": {
"_id": "60612871bd89e52ca08d3ea1",
"postText": "This is an example of a post.",
"createdAt": "Mar 28th, 2021 at 21:08 pm",
"postedBy": {
"_id": "6060a868d856f01738f45185",
"username": null,
"image": null
},
"commentCount": 0,
"comments": []
}
}
}
What am I doing wrong?
Since you're only getting the ref and no additional data, I think you just forgot to populate the user field.
Try:
return await post.populate('postedBy').execPopulate();

MongoDB validation allowing everything

I'm starting to use MongoDB node driver and I can't get validation to work at all.
I created the following validation objects using query:
validator: { $in: [
{ name: { $type: "string" } }
]}
And this JSON Schema:
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name"],
properties: {
name: {
bsonType: "string",
description: "is required and must be a string"
}
}
}
}
Then if I try to insert the following document with this structure {name: 2}, it gets added no failed validation whatsoever.
I've read the mongo and the node driver docs up and down regarding document validation and can't find a way to get this validated. I'm currently using Mongo version 3.6.7 and the node driver version 3.1.4, on an express server version 4.16.3.
This is the whole code:
// create a single user
const createSingleUser = (client, db) => {
db.collection("users").insertOne({
name: 2
}, (err, response) => {
if (err) console.warn(err);
console.log("new user added!!!!");
client.close();
}); // insert one
};
// create collection and add validator
const createUserCollection = client => {
const MongoDriverData = client.db("MongoDriverData");
// create the collection and add validation
MongoDriverData.createCollection( "users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name"],
properties: {
name: {
bsonType: "string",
description: "is required and must be a string"
}
}
}
}, // validator
validationAction: "error"
}, (err, results) => {
console.log( "Collection created!!!" );
// now insert a user
createSingleUser(client, MongoDriverData);
});
};

mongoose populate field using _id of its own document

I'm creating an appliction using MEAN stack in which i've one to one chat feature. I'm using mongoose and have 3 schemas :
Users
{
name: {
type: String,
required: true
},
email: {
type: String
},
phone: {
type: Number,
required: true
},
profile_pic: {
type: String,
default: null
},
password: {
type: String
},
salt: {
type: String
}
}
Messages
{
message : {
type : String,
required : true
},
timestamp : {
type : Number,
required : true
},
from : {
type : String,
required : true
},
conversation_id : {
type : mongoose.Schema.Types.ObjectId,
required : true
}
}
Conversations
{
users : [ {
type: type : mongoose.Schema.Types.ObjectId,
ref : User
}]
}
Now, when user goes to his messenger i want to show him all his past conversations with latest messages so right now i'm exceuting find command on Conversation and populating User
then after getting all conversations i'm executing find command for each conversation to get their latest message, so by this there are so many find operations are done on database in single request. i.e. why i need some solution like populate latest message for each conversation ( like i can populate using _id of conversation )
Edit
Here is the code i'm using right now :
let completeConversations = [];
conversation.find({ "users": req.body.token_data.id }).populate({ path: 'users', select: 'name profile_pic' }).exec((err, conversations) => {
if (err) throw err
if (conversations.length == 0) {
res.status(200);
res.json({ message: "No Conversations Found" })
} else {
conversations.forEach(element => {
messages.find({ conversation_id: element._id }).sort('-timestamp').limit(1).exec((err, message) => {
if (err) {
res.status(200);
res.json({ message: "Latest Message Not Found", conversations })
} else {
element = JSON.parse(JSON.stringify(element));
element.latest = message[0];
completeConversations.push(element);
}
if (completeConversations.length === conversations.length) {
res.json(completeConversations)
}
})
});
}
})
thanks in Advance

What is the mongoose schema of this json example?

I am working on a Node.js project with MongoDb Database .
I need the schema of this json example :
I am working on a Node.js project with MongoDb Database .
I need the schema of this json example
MongoDb document :
{
"container_number": "ddd",
"container_Date": "2/2/2018",
"scannedProductArray": {
"CCR": [
{
"ScannedDate": {
"$date": "2018-03-28T20:54:57.663Z"
},
"productNumber": "4656874974",
"productType": "CCR"
},
{
"ScannedDate": {
"$date": "2018-03-28T20:55:23.698Z"
},
"productNumber": "4656874974",
"productType": "CCR"
}
],
"CCH": [
{
"ScannedDate": {
"$date": "2018-03-28T21:25:16.202Z"
},
"productNumber": "4656874974",
"productType": "CCR"
},
{
"ScannedDate": {
"$date": "2018-03-28T21:26:08.696Z"
},
"productNumber": "4656874974",
"productType": "CCR"
}
]
}
}
container_number: String,
container_Date: String,
scannedProductArray:{CCR:[ScannedDate: {
date:type:Date,default:Date.now
},
"productNumber:Number,
"productType": "String"],CCH[:[ScannedDate: {
date:type:Date,default:Date.now
},
"productNumber:Number,
"productType": "String"]}
May be this one helps you.
I'd like to define schemas like this:
const Product = {
ScannedDate: {
type: Object,
},
productNumber: {
type: String,
},
productType: {
type: String,
default: 'CCR',
}
};
const Item = {
itemName: {
type: [Product],
},
};
const Container = {
container_number: {
type: String,
},
container_Date: {
type: String
},
scannedProductArray: {
type: Object, // Item
}
};
If the CCR/CCH fields are dynamic, I can just use type: Object rather than a certain structure. And I validate these array items by myself instead of mongoose.