How to override mongoose schema - node.js

Lets say I have this schema:
const userSchema = new Schema({
name: {type: String},
email: {type: String},
created: {type: Date,default: Date.now},
deleted: {type: Date,default: undefined}
});
And that I add a few rows:
const user1 = new User({name: 'bob',email: 'bob#google.com'});
const user2 = new User({name: 'mary',email: 'mary#google.com'});
const user3 = new User({name: 'alice',email: 'alice#google.com'});
When calling
User.find({});
I will get all three users above.
However, I want add a function to delete them in a soft way. That's why I have the field "deleted".
By doing this:
const user = User.find({email: 'bob#google.com'});
user.deleted = Date.now();
In mongo, the user bob will have the field deleted NOT undefined.
If I now call again this:
User.find({});
Bob will also be delivered. Of course I can add the flag directly like this:
User.find({deleted: undefined});
But if all database wants to apply this principle, I guess it would be better to centrilize this functionality.
Is this about overriding the mongoose schema? Could somebody point me into the right direction here?

If you are doing a find with no filters then it will return ALL records. If you don't want some users (such as those who have a date in the 'deleted' field) then you need to put in a filter.
find({}) is equivalent to select * from table. It returns ALL records without any filter.

Related

Nested objects are not update

Allora, I'm using mongoose for the first time and I decided to create 2 schemes: the first one represents a user and the second one represents his enquires. Users have an array of enquires like:
var userSchema = new mongoose.Schema({
name: String,
enquires: { type : [Enquire.schema] , "default" : [] },
});
var enquireSchema = new mongoose.Schema({
status: {type: String, 'default': 'pending'},
enquire: String,
});
I see that if I search for an enquire and update its status, it doesn't update the same enquire on the user's array, meaning that they are different object. I don't want to save an array of IDs as it will be the same as a relational database, so I see only 1 solution which is forgetting about the enquire scheme and use only the User scheme. Is it the way mongoose works? For every relationship do I have to insert everything like nested object?
I think you should use references to achieve what you want to achieve.
For more information on mongoose references and populate see Mongoose Populate documentation.
Try this, It may help you.
User Schema :
var userSchema = new mongoose.Schema({
name: String,
enquires: [{ type : mongoose.Schema.Types.ObjectId , ref : 'Enquiry' }]//array of enquiries
});
var User = mongoose.model('User',userSchema );
module.exports = User;
Enquiry Schema :
var enquireSchema = new mongoose.Schema({
status: {type: String, 'default': 'pending'},
enquire: String,
});
var Enquiry = mongoose.model('Enquiry',enquireSchema );
module.exports = Enquiry ;
Working :
create a new Enquiry.
Push it's ID(_id) into user's enquires array.
var enquiry = new Enquiry();
enquiry.enquire = "Dummy enquiry";//set the enquiry
enquiry.save(function(err,result){
if(!err){
//push 'result._id' into users enquires array
}
});
whenever you update an enquiry, it will be automatically updated in
user's document.
use populate to retrieve user's enquiries.
You can embed sub documents (entity) which has id and is like a document or embed native array like a normal property.
And I think the correct definition for yours is :
var enquireSchema = new mongoose.Schema({
status: {type: String, 'default': 'pending'},
enquire: String,
});
var userSchema = new mongoose.Schema({
name: String,
enquires: { type : [enquireSchema] , "default" : [] },
});
If you use refs in embedded link then there are two separate collections and be like relational db's.

Store Country, City and User info using mongoose and nodejs MongoDB

I want to use mongodb on my new project. That is first time, im using mongodb. In relational databases i was saving datas like:
tbl_country > id,name,created_at,etc..
tbl_city > id,country_id,name,created_at,etc...
tbl_user > id,name_surname,city_id,etc...
In this schema i can find a city's country, a user's country, etc... via using foreign keys.
Which way do you suggest to create a schema like this in best performance by nodejs w/ mongodb ?
You can still use foreign keys when you create your schemas. Please check this schemas as examples you have given.
var CountrySchema = new Schema({
name: String,
created_at: Date
});
var CitySchema = new Schema({
countryName: { type: mongoose.Schema.Types.ObjectId, ref: 'Country' },
created_at: Date
});
var UserSchema = new Schema({
name_surname: String,
city: { type: mongoose.Schema.Types.ObjectId, ref: 'City' }
})
mongoose.model('Country', CountrySchema);
mongoose.model('City', CitySchema);
mongoose.model('User', UserSchema);
and when you fetch data, you have to use 'populate' method. For instance:
City.find()
populate('countryName', 'name') // It will bring only name field
.exec(function(err, cities) {
})
Btw. _id s are automatically created by mongo for each data. So you do not need to add id field into your schemas. Hope it helps. Good luck

Deleted Unique Constraint in MongoDB create again with same name

During starting my project some how i define modal as unique in mongoose
let Say:
var CategorySchema = new Schema({
categoryName: { type: String, Unique: true},
discription:String
});
After some day a situation comes and i delete Unique key now my model is:
var CategorySchema = new Schema({
categoryName:String,,
discription:String
});
Now the real Problem is that when i publish and document inserted it still creates indexes of categoryName.
Want to know why this still create and how to recover from these error on production.

Adding a Static, Complex Object to Mongoose/Passport Schema

I use Mongoose and Passport in my web application for the addition of new users into my MongoDB database. I use Google oauth for registering/signing in. In my user schema, I have the following defined for the google method:
//user.js
var userSchema = mongoose.Schema({
google : {
id : String,
token : String,
access_token : String,
email : String,
name : String,
picture : String,
nameInfo : Object,
}
});
I use the following method for user creation:
//passport.js
var newUser = new User();
//newUser.google.token = token;
newUser.google.name = profile.displayName;
newUser.google.nameInfo = profile._json.name
newUser.google.email = profile.emails[0].value;
newUser.google.id = profile.id;
newUser.google.picture = profile._json.image.url + '0';
newUser.google.access_token = token;
You can see that all this data goes under the "google" array in the top level of my user document. How would I add a new, complex, static array? For example, I want a new array at the top level of document in the following format:
newUser.dogs = ["cats":[]}]
I need this particular format based on a dependency in how users should look in my web code. I will eventually be adding data to the "cats" array, but it needs to start out empty. When I try varations of this, I'm only able to get the top level array - ex: my document looks like:
objectid: 1000,
google: [...],
dogs: []
when I need it to look like:
objectid: 1000,
google: [...],
dogs: [{"cats":[]}]
What do I need to change to my schema, either on the schema design, or the data going into the schema?
You want to set inner embedded docs.
Here it is sample, You can create it like this.
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var Trigger = new Schema({
type : {type: String},
value: {type: Number}
});
var Field = new Schema({
label : {type: String},
type: {type: String},
triggers: [Trigger]
});
var Form = new Schema({
fields : [Field],
user_id : {type: String}
});

How to declare schematype/datatype of a field in mongoose which is the objetid of an item in another collection?

I am a bit confused by something in MongoDB, when using Mongoose, since I am new to it. I have two collections: authors and posts.
each author in the authors collection have the mongodb inbuilt id associated with them, which as per my understanding is of the schematype/datatype Objectid.
Now in my posts collection, I have a field which has is called author, which should have the value of the author's Objectid, similar to the foreign key concept in SQL.
My question is, which schematype/datatype should I declare the author field in the posts collection? Should I put it as Objectid? If so, would it not auto-increment and not be settable?
Mockup Of Schemas:
var authors = new mongoose.Schema({
name: String,
email: String
});
var posts = new mongoose.Schema({
title: String,
author: **??**
});
Any help would be hugely appreciated!
You can use population for that:
var authors = new mongoose.Schema({
name: String,
email: String
});
var posts = new mongoose.Schema({
title: String,
author: { type: Schema.Types.ObjectId, ref: 'Author' }
// assuming the model will be called 'Author'
});
To use:
// Get 'author' some how (create a new one, query the
// database for existing authors, etc);
...
// Create a new post and associate it with 'author' by referencing its `_id`:
var post = new Post({
...
author : author._id
});
post.save(...);
The documentation linked above also shows how you can get Mongoose to automatically retrieve the author document when you're querying posts.

Resources