Mongoose TTL not working on Timestamps - node.js

I have issue getting mongoose timestamps work with mongoose expires. I see no MongoDB TTL Index on updatedAt.
schema:
const AdminSessionSchema = mongoose.Schema({
UID: String,
device: String,
updatedAt : { type: Date, expires: 60 }
}, { collection: 'admin.session', timestamps: true });
mongoshell:
> db.admin.session.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "development.admin.session"
}
]
Is this the right way to make it work? or am I missing something.

Related

how to update specific subdocument in array with mongoose

postSchema
let postSchema = new mongoose.Schema({
data : Buffer,
contentType : String,
caption : String,
likes : [mongoose.ObjectId],
likesCount : {type :Number, default : 0},
comment :[{userId :mongoose.ObjectId, cmnt : String, reply :[{}]}],
commentCount : {type :Number, default : 0},
date : {type : Date, default: Date.now}
})
userSchema
let userSchema = new mongoose.Schema({
qr : {
data : Buffer,
contentType : String
},
profile_pic:{
data:Buffer,
contentType : String
},
first_name:String,
last_name:String,
email:{
type:String,
unique:true
},
mobile_number:Number,
DOB : Date,
gender:{
type : String,
enum : ["Male","Female","Other"]
},
password : {
type : String
},
address:{
city : String,
state : String
},
followers : {
type : [mongoose.ObjectId]
},
followersCount : {
type : Number,
default : 0
},
following : {
type : [mongoose.ObjectId]
},
followingCount : {
type : Number,
default : 0
},
//this is my post schema
posts : [postSchema],
postsCount :{type :Number, default : 0},
reset_password_token : {
OTP:Number,
is_varify_password_token : {
type:Boolean,
default : false
},
time : {
type : Date,
}
}
})
** 1) i want to find specific user
2) after finding user i want to find and update specific post (caption) in array of posts **
i have tried but not working
await USERMODEL.findOneAndUpdate({_id:req.user._id,posts:{$elemMatch:{_id: req.params.postId}}},{"posts.$.caption ":caption})mongodb document image
PLEASE HELP I AM NEW TO MONGODB
**by mistake I have pasted some code out of block please do not mind **
It looks like your post is mostly code; please add some more details

How to update document data in nested object in MongoDB?

This is default schema model :-
const UserSettings = new Schema({
ID: { type: Number, required: true, exists: false, unique : true },
UserID : Number,
Account : {
Name : String,
Email : { type: String, required: "email id is required", exists: false, unique : true },
UserName : String,
isFacebook : {type : Boolean, default : false}
},
Notification : {
Trending : {
isEmail : {type : Boolean, default : true},
isPush : {type : Boolean, default : true},
Button : {
isDaily : {type : Boolean, default : false},
isWeekly : {type : Boolean, default : false},
isOff : {type : Boolean, default : false}
}
},
Recommanded : {
isEmail : {type : Boolean, default : true},
isPush : {type : Boolean, default : true},
Button : {
isDaily : {type : Boolean, default : false},
isWeekly : {type : Boolean, default : false},
isOff : {type : Boolean, default : false}
}
}
}
});
When I save values it will enter the default fields values in schema,
"Account" : {
"Email" : "ted#gmail.com",
"isFacebook" : true,
"Name" : "ted"
},
"Notification" : {
"Trending" : {
"Button" : {
"isDaily" : false,
"isWeekly" : false,
"isOff" : false
},
"isEmail" : true,
"isPush" : true
},
"Recommanded" : {
"Button" : {
"isDaily" : false,
"isWeekly" : false,
"isOff" : false
},
"isEmail" : true,
"isPush" : true
}
}
In update case I have to passed selected arguments like only need to Update
Account{
Email : "ted1#gmail.com"
},
Notification {
Trending {
isPush : false,
}
}
Then how would I used mongo update query?
I have tried this solutions to update value but it will removed existing value :-
return UserSettings.updateOne(
{$and: [{ UserID: args.UserID },{ Status : 1 }]},
{ $push : { "Account": args.Account }},
{
upsert: true,
returnNewDocument: true
},
);
and one more this :-
return UserSettings.updateOne(
{$and: [{ UserID: args.UserID },{ Status : 1 }]},
args,
{
upsert: true,
returnNewDocument: true
},
);
Try this:
let Account = args.Account
let condition = { $and: [ { UserID: args.UserID },{ Status : 1 }]}, { 'Account.Email': args.Account.Email }] }; // here check email in sub document
UserSettings.updateOne(condition, { $set: { Account: Account } }).exec((err, data) => {
if (err || data.nModified == 0) {
UserSettings.updateOne({ UserID: args.UserID }, { $push: { Account: Account } }).exec((err, data) => {
return {'message':'Updated successfully','data':data}; // Send proper response as per your need
});
}
else {
return {'message':'Failed'};// Send proper response as per your need
}
});

mongodb: expires not working

In mongoose 5.0.6, I'm hoping this schema to expire documents 1min after creation:
const InvitationTokenSchema = new Schema(
{
token: { type: String, required: true },
createdAt: { type: Date, default: Date.now, expires: '1m' },
userId: { type: Schema.Types.ObjectId, ref: 'User' },
},
{
usePushEach: true,
},
);
However it simply doesn't work - all documents just persists in mongo, not being removed.
In mongo shell, getIndexes() shows the following:
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "mydb.invitationtokens"
},
{
"v" : 2,
"key" : {
"createdAt" : 1
},
"name" : "createdAt_1",
"ns" : "mydb.invitationtokens",
"expireAfterSeconds" : 60,
"background" : true
}
]
What possibly could be the reason?
As I see you code, its right.
Also, the value should be String and you can use '1m' as well.
You need to update the mongoose to the latest version.
Use: npm update mongoose
For more details search for "expires" here: http://mongoosejs.com/docs/api.html

mongoose: update field, push object in array [duplicate]

This question already has answers here:
Stop Mongoose from creating _id property for sub-document array items
(7 answers)
Closed 7 years ago.
I would like to add an element in an array in a mongo database:
db.keypairs.update( {pubkey: "1234567890"}, { $push: {listTxId: {txHash: "yyy", spent: false} } } )
The result is perfect:
listTxId" : [ { "txHash" : "xxx", "spent" : true },{ "txHash" : "yyy", "spent" : false } ]
Now I would like to do the same with node.js and mongoose
var res = wait.forMethod(Keypair,'update', {pubkey: "1234567890"}, { $push: { "listTxId": {"txHash":"zzz", "spent":false} } } );
Keypair is my node.js model for the mongoose collection:
var Keypair = require('./app/models/Keypair');
and wait.forMethod comes from a node module:
var wait = require('wait.for');
In the result, I have this "_id" element :
{ "txHash" : "zzz", "spent" : false, "_id" : ObjectId("56561571fea5d9a10a5771fd") }
QUESTION: where this ObjectId come from ? How can I get rid of it ?
UPDATE: mongoose schema:
var keypairSchema = mongoose.Schema({
userId : { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
pubkey : String,
privkeyWIF : String, // temp
balance : Number,
listTxId : [{
txHash : String,
spent : Boolean
}],
walletId : { type: mongoose.Schema.Types.ObjectId, ref: 'Wallet' },
description : { type: String, maxlength: 40 },
comments : String,
isMasterKey : { type: Boolean, default: false },
date : Date
});
Mongoose will put ids in your subdocument arrays. listTxId is a subdocument array. You can add _id: false to your schema to prevent this:
var keypairSchema = mongoose.Schema({
userId : { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
pubkey : String,
privkeyWIF : String, // temp
balance : Number,
listTxId : [{
_id: false,
txHash : String,
spent : Boolean
}],
walletId : { type: mongoose.Schema.Types.ObjectId, ref: 'Wallet' },
description : { type: String, maxlength: 40 },
comments : String,
isMasterKey : { type: Boolean, default: false },
date : Date
});

Can't get mongoose 'populate' to work

I am stuck on populating a ref field in a simple mongoose (3.8.8) query.
It's probably a stupid issue but i can't actually sort it out..
var Schema = mongoose.Schema;
var ItemSchema = new Schema({
description: { type: String },
comments: [ { type:Schema.Types.ObjectId, ref:'Comment'} ],
created: { type: Date, default: Date.now }
});
var Item = mongoose.model('Item', ItemSchema);
var CommentSchema = new Schema({
text: { type: String },
item_id: { type:Schema.Types.ObjectId, ref:'Item'} ,
created: { type: Date, default: Date.now }
});
var Comment = mongoose.model('Comment', CommentSchema);
Item.find().populate('comments').exec(function(err,item){
console.log('Item ',item)
})
the data is:
/* item0 */
{
"_id" : ObjectId("53da00cc5ddd29442463e716"),
"description" : "item1",
"created" : ISODate("2014-07-31T08:39:40.475Z"),
"comments" : [],
"__v" : 0
}
/* item1 */
{
"_id" : ObjectId("53da00cc5ddd29442463e717"),
"description" : "item2",
"created" : ISODate("2014-07-31T08:39:40.478Z"),
"comments" : [],
"__v" : 0
}
/* comment0 */
{
"_id" : ObjectId("53da01e9ef4ecaa0231fdc8d"),
"item_id" : ObjectId("53da00cc5ddd29442463e716"),
"text" : "comment1",
"created" : ISODate("2014-07-31T08:44:25.768Z"),
"__v" : 0
}
It just won't work as expected, not populating the 'comments' array, tho in my comments collection the item_id is populated correctly.
What's the problem?
Thanks in advance

Resources