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.
Related
Suppose I have two schemas on MongoDB:
const personSchema = Schema({
_id: Schema.Types.ObjectId,
name: String,
email: String,
things: [{ type: Schema.Types.ObjectId, ref: 'Thing' }]
});
const thingSchema = Schema({
_id: Schema.Types.ObjectId,
title: String,
fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
Every time a user logs in, I would like to show the things that they have posted, as well as the fans that are following each of the things. I am able to use populate and select to get to that:
const user = await personModel
.findOne({ _id: req.user._id })
.populate({
path: "things",
select: ["title", "fans"]
}),
However, I am only getting the id of each fan, and not the fan's name and email. I can't quite figure out how to use populate to reference the person collection again.
The outcome I am trying to achieve is that:
the user object would have an array of things
the thing object would have an array of fans
the fan object would have two values - name and email of the fan
You can do nested population with:
const user = await personModel
.findOne({ _id: req.user._id })
.populate({
path: 'things',
select: ['title', 'fans'],
populate: { path: 'fans' },
})
.exec();
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)});
This is my user schema :
const userSchema = new Schema({
email: String,
username: String,
password: String,
secretToken: String,
active: Boolean,
type: String
}, {
timestamps: { // this will give us the detail when the account is created
createdAt: 'createdAt',
updatedAt: 'updatedAt'
}
});
this is my requirement Schema:
const requirementSchema = new Schema({
name: String,
age: String,
class: String,
subject: String,
email: String
}, {
timestamps: { // this will give us the detail when the requiremnt is created
createdAt: 'createdAt',
updatedAt: 'updatedAt'
}
});
how can I bring id from user schema to the requirement schema as secondary key?
I think mongodb is not meant for relationship. I could led to very bad practice if your database grow. But you can try https://docs.mongodb.com/manual/reference/database-references/#DatabaseReferences-DBRef for Database References.
There is no primary key foreign key concept in Mongodb. and normalization is also discouraged in mongodb.
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?
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);