How to add schema to another schema array? - node.js

I have address schema and customer schema. I have a field address array inside my customer schema. I will be sending an adress model as my req body and customer id as req param. How can I save that adress to adresses array which is declared inside customer schema?
This is my Customer Schema
const customerSchema = mongoose.Schema ({
_id: mongoose.Schema.Types.ObjectId,
name: String,
phone_number: String,
password: String,
type:{type:String,enum:['admin','user']},
adresses:['Adress'],
orders:[{type: mongoose.Schema.Types.ObjectId, ref: 'Order'}]
});
This is my Adress Schema
const addressSchema= mongoose.Schema({
_id:mongoose.Types.ObjectId,
postalCode:Number,
city:String,
district:String,
neighborhood:String,
streetNumber:String,
no:Number,
buildingName:String,
apartmentNumber:Number,
floor:Number,
coordinates:{
latitude:Number,
longitude:Number
},
addressName:String,
customerId: {type: mongoose.Schema.Types.ObjectId,ref:'Customer'}
});
I could not figure out how am ı going to do this. I am finding the customer which I will going to push my address to like this.
This is how I get the specific customer
Customer.find({_id:req.params.customerId},(err,data)=>{
if(err) return next(err);
else{
//What I am going to do here?
}
});
First what type should I put inside the addresses array which is inside Customer Schema?
Second after finding the customer which I am going to add address to, what should I do? Mongoose 5.4.11 documentation was not enough for me. This link seemed what I needed but I did not figure out how to accomplish this problem.
https://mongoosejs.com/docs/subdocs.html

OK, so basically what You look for is: association. You need to establish a connection between User and Customer model.
We will say that Address belongs to the User and User reference Address object by for example id.
Consider an example:
const personSchema = Schema({
_id: Schema.Types.ObjectId,
name: String,
age: Number,
stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
const storySchema = Schema({
author: { type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);
Now let's try to assign an author to particular created story:
const author = new Person({
_id: new mongoose.Types.ObjectId(),
name: 'Ian Fleming',
age: 50
});
author.save(function (err) {
if (err) return handleError(err);
const story1 = new Story({
title: 'Casino Royale',
author: author._id // assign the _id from the person
});
story1.save(function (err) {
if (err) return handleError(err);
// thats it!
});
});
When you define relation between Story and Person, it is easy to manipulate references between them.
In your case you should define a reference in models and then you are able to manipulate the fields:
Customer.findOne({_id:req.params.customerId}, function(error, customer) {
if (error) {
return handleError(error);
}
customer.address = newAddress; // set customer's address to the desired address
// console.log(customer.address.city);
});
Check doc for more.

Related

Mongoose Model ObjectId References Not Working

I'm working with Mongoose models and references. I've been using the code from mongoose's website where it talks about the populate method and references. I am trying to have it save the respective "referenced" ids in both models. It is only saving the reference ids in the story model. Here is the code:
Update: Added schemas at the top to help:
var personSchema = Schema({
_id: Schema.Types.ObjectId,
name: String,
age: Number,
stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
author: { type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);
(end of schemas)
var author = new Person({
_id: new mongoose.Types.ObjectId(),
name: 'Ian Fleming',
age: 50
});
author.save(function (err) {
if (err) return handleError(err);
var story1 = new Story({
title: 'Casino Royale',
author: author._id // assign the _id from the person
});
story1.save(function (err) {
if (err) return handleError(err);
// thats it!
});
});
When you run this code, it generates this in mongo:
db.people.find()
{ "_id" : ObjectId("5be0a37f1dd61a343115e2c8"), "stories" : [ ], "name" : "Ian Fleming", "age" : 50, "__v" : 0 }
db.stories.find()
{ "_id" : ObjectId("5be0a37f1dd61a343115e2c9"), "title" : "Casino Royale", "author" : ObjectId("5be0a37f1dd61a343115e2c8"), "__v" : 0 }
It appears to not be storing any ids in the people collection within "stories." Wouldn't you want to save the stories ids in the people collection as well?
I tried to modify the code to make it work with (moved the author save function, until after the story id is set):
var author = new Person({
_id: new mongoose.Types.ObjectId(),
name: 'Ian Fleming',
age: 50
});
var story1 = new Story({
_id: new mongoose.Types.ObjectId(),
title: 'Casino Royale',
author: author._id // assign the _id from the person
});
author.stories = story1._id;
author.save(function (err) {
if (err) return handleError(err);
story1.save(function (err) {
if (err) return handleError(err);
// thats it!
});
This gives me an author undefined.
Mongo wouldn't automatically add to the Person "stories" field just because you added a Story object.
You don't really need to store the story ids in Person objects anyway, as you can always get a list of stories by an author with
db.stories.find({author: <id>})
Storing in both places would create redundant information and you'd have to pick one to be the truth in the case of a mismatch. Better to not duplicate, methinks.
UPDATE:
References appear to help you populate referenced fields in queries automatically. According to this post you can retrieve an author and their stories like this:
db.persons.find({_id: <id>}).populate('stories')
Haven't personally used this but it looks pretty handy.
Mongoose docs for populate: https://mongoosejs.com/docs/populate.html

Populate method is not populating data when associated to another model

I have associated my User schema model with Post schema model, and I'm trying to populate post model data into user model, but I always get null value.
I'm not sure what I am doing wrong. Please help. thanks in advance!
userSchema = new Schema({
name: String,
email: String,
posts: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Post"
}]
});
postSchema = new mongoose.Schema({
title: String,
content: String
});
and here is my query to achieve the above-said result (assume that post and user data is created properly):
User.find({name: 'Vignesh'}).populate("posts").exec(function(err, post){
if(!err){
console.log("..........populated posts of User........");
console.log(post);
} else {
console.log(err);
}
});

Mongoose - don't allow documents to have identical arrays

I want to create a database schema where a document cannot have an array that is identical to that of another document. So, say I have the schema conversations:
var ConversationSchema = new Schema({
name: String,
participants: {
type: [{
type: Schema.Types.ObjectId,
ref: 'User'
}]
}
});
Now if I create two conversations with the same participants, how can I validate this so that the second one will fail, but the third will not?
var conversation1 = new Conversation({
name: "Hello",
participants: ['12345', '09876']
});
var conversation2 = new Conversation({
name: "World",
participants: ['12345', '09876']
});
var conversation3 = new Conversation({
name: "Group chat",
participants: ['12345', '09876', '13579']
});
conversation1.save(); // Valid
conversation2.save(); // Invalid - conversation already exists
conversation3.save(); // Valid
I guess you could use some custom Mongoose validation before saving your data.
But this is not really a schema thing, as Kevin said in his comment, since you will need to make a database query to compare already existing array with the new one.
Something like this (not tested):
function checkArray(arr) {
// here make a call to the db to compare existing array with arr
}
var ConversationSchema = new Schema({
name: String,
participants: {
type: [{
type: Schema.Types.ObjectId,
ref: 'User',
validate: checkArray
}]
}
});
No better idea for now.

Query Mongoose Schema. nested array of comments

I have venues, which each have a comments section. Each comment is a Mongoose Comment schema. Each comment has a creator property, which is a User schema. I'm trying to find all comments a specific user has posted. How can I do this?
var VenueSchema = new mongoose.Schema({
comments: [{
type : mongoose.Schema.Types.ObjectId,
ref: 'Comment',
default: []
}]
},
{minimize: false});
var CommentSchema = new mongoose.Schema({
creator: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}, {minimize: false});
var UserSchema = new mongoose.Schema({
token: String,
venues: [{ //in case we want users to save their favorite venues
type : mongoose.Schema.Types.ObjectId,
ref: 'Venue'
}]
});
I have tried
Venue.find({
"comments.creator": "55f1fa1263877ed0067b78c0"
}, function(err, docs) {
console.log(docs);
res.send(docs);
})
but it returns an empty array. The "55f1fa1263877ed0067b78c0" is a sample creator _id. Thanks in advance!
you cannot search creater by its id inside Venue collection becouse it collects only Comment ID. So in order to search creater by its id you need to change like below:
var VenueSchema = new mongoose.Schema({
comments: [CommentSchema]
},
{minimize: false});
var CommentSchema = new mongoose.Schema({
creator: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}, {minimize: false});
var UserSchema = new mongoose.Schema({
token: String,
venues: [{ //in case we want users to save their favorite venues
type : mongoose.Schema.Types.ObjectId,
ref: 'Venue'
}]
});
As venueSchema is storing only ref to comments (which would be comments _id), you will not be able to query comment using venue model. Either you have embed comment document into comments array of venue schema.
Or
Just query the comment collection using comment model as below
Comment.find({
"creator": "55f1fa1263877ed0067b78c0"
}, function(err, docs) {
console.log(docs);
res.send(docs);
})

MongoDB Mongoose schema design

I have a schema design question. I have a UserSchema and a PostSchema.
var User = new Schema({
name: String
});
var Post = new Schema({
user: { type: Schema.Types.ObjectId }
});
Also, user is able to follow other users. Post can be liked by other users.
I would like to query User's followers and User's following, with mongoose features such as limit, skip, sort, etc. I also want to query Post that a user likes.
Basically, my only attempt of solving this is to keep double reference in each schema. The schemas become
var User = new Schema({
name: String,
followers: [{ type: Schema.Types.ObjectId, ref: "User" }],
following: [{ type: Schema.Types.ObjectId, ref: "User" }]
});
var Post = new Schema({
creator: { type: Schema.Types.ObjectId, ref: "User" },
userLikes: [{ type: Schema.Types.ObjectId, ref: "User" }]
});
so, the code that will be used to query
// Find posts that I create
Post.find({creator: myId}, function(err, post) { ... });
// Find posts that I like
Post.find({userLikes: myId}, function(err, post) { ... });
// Find users that I follow
User.find({followers: myId}, function(err, user) { ... });
// Find users that follow me
User.find({following: myId}, function(err, user) { ... });
Is there a way other than doing double reference like this that seems error prone?
Actally, you don't need the double reference. Let's assume you keep the following reference.
var User = new Schema({
name: String,
following: [{ type: Schema.Types.ObjectId, ref: "User" }]
});
You can use .populate() to get the users you're following:
EDIT: added skip/limit options to show example for pagination
User.findById(myId).populate({ path:'following', options: { skip: 20, limit: 10 } }).exec(function(err, user) {
if (err) {
// handle err
}
if (user) {
// user.following[] <-- contains a populated array of users you're following
}
});
And, as you've already mentioned ...
User.find({following: myId}).exec(function(err, users) { ... });
... retrieves the users that are following you.

Resources