This is my schemes:
var authUserScheme = mongoose.Schema({
token: String,
ip: String,
valid: {type: Date, default: Date.now(), expires: '1m' },
}, {_id: false});
var usersSchema = mongoose.Schema({
// OTHER THINGS
auth : [ authUserScheme ],
// other things
});
When i set an 'auth' path, mongodb deletes the entire document, but i want to delete only the auth row when expire date... It is possible?
Sorry for my english, i speak spanish.
You can't use a TTL index to delete a portion of a document on expiry.
However, it looks like your authUserScheme is really more of a session concept than an embedded document.
A better approach would be to use a reference from the authUserScheme to the related user, eg:
var authUserSchema = mongoose.Schema({
token: String,
ip: String,
valid: {type: Date, default: Date.now(), expires: '1m' },
user: { type: Number, ref: 'User' }
});
var userSchema = mongoose.Schema({
name: String,
// Other fields
})
var AuthUser = mongoose.model('AuthUser', authUserSchema);
var User = mongoose.model('User', userSchema);
Related
I am doing a query on my database using Mongoose to retrieve all documents in a collection. Currently there is only one document in the collection. It returns the document and looks fine, but I cannot access some of the properties.
Code snippet:
User.find()
.then((response)=>{
console.log(response);
console.log();
console.log(response[0]._id);
console.log(response[0].name);
console.log(response[0].email);
console.log(response[0].zipCode);
console.log(response[0].dateTime);
console.log(response[0].ipAddr);
console.log(response[0].pageVisited);
}).catch((err)=>{console.log(err)});
Result:
[
{
_id: 5f6d4dc312c76000170c5c43,
name: 'Bob',
email: 'bob#mail.com',
zipCode: '12345',
pageVisited: 'p1m2549',
dateTime: 2020-09-25T01:54:11.152Z,
ipAddr: '111.111.111.111',
__v: 0
}
]
5f6d4dc312c76000170c5c43
Bob
bob#mail.com
undefined
undefined
undefined
undefined
What could be causing this bizarre behavior? It really doesn't make any sense that I can access some of the properties but not others.
That could be because these elements not be defined in the Schema
Define Schema as mentioned below
var Schema = mongoose.Schema;
var UserSchema = new Schema({
name: String,
email: String,
zipCode: String,
pageVisited: String,
dateTime: Date,
ipAddr: String,
__v: Number
});
var User = mongoose.model('users', UserSchema );
User.find()
.then((response)=>{
console.log(response);
console.log();
console.log(response[0]._id);
console.log(response[0].name);
console.log(response[0].email);
console.log(response[0].zipCode);
console.log(response[0].dateTime);
console.log(response[0].ipAddr);
console.log(response[0].pageVisited);
console.log(response[0].__v);
}).catch((err)=>{console.log(err)});
I have had the following User schema with already a good amount of users saved in the db:
const userSchema = new Schema({
...
country: String,
authorities: [{ code: String, description: String }]
...
});
I have decided to save authorities by country, so the schema becomes :
const userSchema = new Schema({
...
country: String,
authorities: [{
country: String,
authorities: [{ code: String, description: String }]
}]
...
});
My question is, how do I update already saved users to reflect schema update?
NB: there is only one country right now.
This is a MERN app, hosted on github, and it works perfectly on localhost. Unfortunately, it does not work on Heroku.
The issue is the API request, it must return an object and populate an array of OIDs (see Department Model). API request is working. I'm getting the data from MLab, but it doesn't populate... instead returns: "surveys":[]
API File
router.get('/department_data/:d_oid', function(req, res) {
Department.findOne({_id: req.params.d_oid}).populate("surveys").exec(function(err,doc){
if(err) throw(err)
res.send(doc)
})
});
Department Model
**Department Model**
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
// Create the survey schema
var departmentSchema = new Schema({
department_name: {
type: String,
trim: true,
required: true
},
surveys: [{
type: Schema.Types.ObjectId,
ref: 'Surveys'
}],
participants: [{
type: String
}],
create_date: {
type: Date,
default: Date.now
},
created_by: {
type: Schema.Types.ObjectId,
ref: 'Created_By'
},
});
departmentSchema.index({ department_name: 1, created_by: 1}, {unique: true});
const Department = mongoose.model('Departments', departmentSchema);
module.exports = Department;
Survey Model
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
// Create the survey schema
var surveySchema = new Schema({
survey_name: {
type: String,
trim: true,
required: true
},
questions: [{
type: Schema.Types.ObjectId,
ref: 'Questions'
}],
created_date: {
type: Date,
default: Date.now
}
});
const Survey = mongoose.model('Surveys', surveySchema);
module.exports = Survey;
Solved.
The problem was in the database: the ref OIDs got scrambled with a previous update, so when it was trying to populate, Mongoose couldn't find any matching OIDs.
Solution: we had to purge and re-seed. When the correct OID references exist, this code works as expected in localhost & Heroku.
I have two mongoose schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var itemSchema = new Schema({
name: {type: String, required: true, max: 25, trim: true},
price: {type: Number, required: true, trim: true, default: 0},
tax: {
type: Schema.Types.ObjectId,
ref: "Store"
}
});
module.exports = mongoose.model('Item', itemSchema);
The second Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var storeSchema = new Schema({
name: {type: String, required: true, trim: true},
taxes: [
{
name: String,
rate: Number
}
]
});
module.exports = mongoose.model('Store', storeSchema);
What I want to do is populate the itemSchema tax object with the storeSchema taxes array of object. every time I pushed a new tax object to the taxes array mongoose created an ObjectId. I stored that ObjectId in my itemSchema Tax. I want to use that _id to retrieve the store taxes that matches the itemSchema _id.
I have tried this so far, but I get no in the tax attribute.
Item.find().populate("tax", "taxes").exec(function (err, docs) {
if (err) return console.error(err);
console.log(items);
});
Try this query
Item.find().populate({
path: 'tax',
select: 'taxes'
}).exec(function (err, docs) {
if (err) {
console.error(err);
} else {
console.log(docs);
}
});
Item.find().populate(path:"tax", model: )
Mention your item model file name... don't use "" or '' for the file name, simply add the file name.
Use Item.find().populate("Store", "taxes") instead of Item.find().populate("tax", "taxes").
I have two schemas (using mongoose) like below:
var PostSchema = new Schema({
name: String,
content: String,
likes: [{
type: String,
ref: 'User'
}],
...
})
var UserSchema = new Schema({
name: String,
pinnedPosts: [{
type: String,
ref: 'Post'
}],
...
})
Now I want to get all posts with two new populated fields: isLiked and isPinned depend on the auth state. If the user hasn't signed in (auth is null) then all these two fields are false. If user has signed in and had liked the post, isLiked is true... Can I do it when I query the post?