Mongoose ODM saves wrong model name in MongoDB collection - javascript

Hello Stackoverflowers!
I got a strange issue with Mongoose creating a collection named "Safes".
here is my example code:
const mongoose = require('mongoose')
mongoose.connect('mongodb://mongodb:27017/test', { useNewUrlParser: true })
const Safe = mongoose.model('Safe', { name: String })
const safe = new Safe({ name: 'foobar' })
safe.save().then(() => console.log('done'))
when I open the database shell and issue this command:
mongo test --eval "db.getCollectionNames()"
its responds with:
MongoDB shell version v4.0.6
connecting to: mongodb://127.0.0.1:27017/test?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("f9cfa8b9-58e2-40b8-9907-ecd18039935a") }
MongoDB server version: 4.0.6
[ "saves" ]
Now, I tried to create a model with a collection names "Safes" and mongoose seems to change it from safes > saves ...
Has mongoose some kind of protected models that cannot be used?

Seems like they set a rule on words ending with "fe" because they normally convert to plural as "ves" (knife -> knives).
You can set your own collection name by adding another argument to Schema:
const safeSchema = new Schema({ name: String }, { collection: 'safes' })

Mongooses util.toCollectionName generates a name of the collection based on the Schema name. It does use some regexes, one of them being:
[/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'],
Which maches safe and replaces it with saves.
source

Related

How to find key with type objectId , ref to <some model>

I have created a Notes model having schema as shown below
const notesschema = new Schema({
user :{
type : Schema.Types.ObjectId,
ref : 'User',
required : true
},
problem : {
type : Schema.Types.ObjectId,
ref : 'Problems',
required : true
},
content : {
type : 'string'
}
},{
timestamps : true
})
To show the User his notes for a particular task/problem I am trying to fetch notes and show to him and possibly update if he do some changes and save, The problem is with this schema I dont know how to write <model.findById >API to find notes from my notes model having particular user and specific task/problem.Which I would know the Id of.
With this particular schema , and my current knowledge i would have to write So much code. So if there is any easier way to do this task is welcomed, I was also thinking to change my schema and just placing my user id in my schema instead of whole user and finding notes from my database
edit : as suggested by all the answers we can simply find using user.id which I thought initially would not word as that was just the path, but which stores actually user.id
You create the notes' collection the same way you're doing it,
const notesSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User', // # the name of the user model
required: true
},
problem: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Problem', // # the name of the user model
required: true
},
content: String
})
Then you'll create the model of the notesSchema as follows:
const NoteModel = mongoose.model('Note', notesSchema, 'notes')
export them so you can use them in your controllers:
module.exports = {
NoteModel,
notesSchema
}
or if you're using +es6 modules (think of, if you're using TypeScript):
export default {
NoteModel,
notesSchema
}
This will result in creating the following table (collection) in the database:
Let's think of the following challenges:
To get all the notes:
NoteModel.find({})
To get all the users:
UserModel.find({}) // you should have something like this in your code of course
To get all the problems:
ProblemModel.find({}) // you should have something like this in your code of course
To get all the notes of a user:
NotesModel.find({ user: USER_ID })
To search for notes by problems:
NotesModel.find({ problem: PROBLEM_ID })
Now, the above is how you do it in mongoose, now let's create a RESTFUL controller for all of that: (assuming you're using express)
const expressAsyncHandler = require('express-async-handler') // download this from npm if you want
app.route('/notes').get(expressAsyncHandler(async (req, res, next) => {
const data = await NotesModel.find(req.query)
res.status(200).json({
status: 'success',
data,
})
}))
The req.query is what's going to include the search filters, the search filters will be sent by the client (the front-end) as follows:
http://YOUR_HOST:YOUR_PORT/notes?user=TheUserId
http://YOUR_HOST:YOUR_PORT/notes?problem=TheProblemId
http://YOUR_HOST:YOUR_PORT/notes?content=SomeNotes
const notesschemaOfUser = await notesschema.findOne({user: user_id});

Mongo DB - unable to retrieve object stored in type:Array

I'm fairly new to MongoDB and have started to learn about relationships. I'm running into an issue where i'm trying to store an array of objects into one of my collection models. Basically the array is storing fine in the sense that if I look at it in compass all the correct information is there. The issue lies with retrieving the array, here is looks like the object in my array has been flattened to a string as it's just retrieving somthing like this:
Note: i'm using node Express as my BE framework
members: [ [Object] ] } ]
Here is my model below:
const teamSchema = new Schema({
name:{
type:String,
trim:true,
required:'Please enter a team name'
},
owner:{
type:mongoose.Schema.ObjectId,
ref:'User'
},
members:{
type:Array,
}
});
And here is how I use the model in Node:
const team = new Team({
name:req.body.teamName,
owner:req.user._id,
members:[{
id:req.user._id,
privilege:'admin'
}]
})
try {
await team.save();
} catch(error) {
console.log(error)
}
Here is what it looks like stored in MongoDB Compass
But when retrieving it and trying to modify it like so:
const team = await Team.find({'_id':teamId});
finds it no problem but the members array just displays as what I mentioned before:
members: [ [Object] ] } ]
can anyone tell me where I might be going wrong? Think it might be to do with the way i'm saving it rather than retrieving it
Try to use the projection field of the findto return the array in the searched element:
const team = await Team.find({'_id':teamId}, {'members': 1});

Mongoose find/update subdocument

I have the following schemas for the document Folder:
var permissionSchema = new Schema({
role: { type: String },
create_folders: { type: Boolean },
create_contents: { type: Boolean }
});
var folderSchema = new Schema({
name: { type: string },
permissions: [ permissionSchema ]
});
So, for each Page I can have many permissions. In my CMS there's a panel where I list all the folders and their permissions. The admin can edit a single permission and save it.
I could easily save the whole Folder document with its permissions array, where only one permission was modified. But I don't want to save all the document (the real schema has much more fields) so I did this:
savePermission: function (folderId, permission, callback) {
Folder.findOne({ _id: folderId }, function (err, data) {
var perm = _.findWhere(data.permissions, { _id: permission._id });
_.extend(perm, permission);
data.markModified("permissions");
data.save(callback);
});
}
but the problem is that perm is always undefined! I tried to "statically" fetch the permission in this way:
var perm = data.permissions[0];
and it works great, so the problem is that Underscore library is not able to query the permissions array. So I guess that there's a better (and workgin) way to get the subdocument of a fetched document.
Any idea?
P.S.: I solved checking each item in the data.permission array using a "for" loop and checking data.permissions[i]._id == permission._id but I'd like a smarter solution, I know there's one!
So as you note, the default in mongoose is that when you "embed" data in an array like this you get an _id value for each array entry as part of it's own sub-document properties. You can actually use this value in order to determine the index of the item which you intend to update. The MongoDB way of doing this is the positional $ operator variable, which holds the "matched" position in the array:
Folder.findOneAndUpdate(
{ "_id": folderId, "permissions._id": permission._id },
{
"$set": {
"permissions.$": permission
}
},
function(err,doc) {
}
);
That .findOneAndUpdate() method will return the modified document or otherwise you can just use .update() as a method if you don't need the document returned. The main parts are "matching" the element of the array to update and "identifying" that match with the positional $ as mentioned earlier.
Then of course you are using the $set operator so that only the elements you specify are actually sent "over the wire" to the server. You can take this further with "dot notation" and just specify the elements you actually want to update. As in:
Folder.findOneAndUpdate(
{ "_id": folderId, "permissions._id": permission._id },
{
"$set": {
"permissions.$.role": permission.role
}
},
function(err,doc) {
}
);
So this is the flexibility that MongoDB provides, where you can be very "targeted" in how you actually update a document.
What this does do however is "bypass" any logic you might have built into your "mongoose" schema, such as "validation" or other "pre-save hooks". That is because the "optimal" way is a MongoDB "feature" and how it is designed. Mongoose itself tries to be a "convenience" wrapper over this logic. But if you are prepared to take some control yourself, then the updates can be made in the most optimal way.
So where possible to do so, keep your data "embedded" and don't use referenced models. It allows the atomic update of both "parent" and "child" items in simple updates where you don't need to worry about concurrency. Probably is one of the reasons you should have selected MongoDB in the first place.
In order to validate subdocuments when updating in Mongoose, you have to 'load' it as a Schema object, and then Mongoose will automatically trigger validation and hooks.
const userSchema = new mongoose.Schema({
// ...
addresses: [addressSchema],
});
If you have an array of subdocuments, you can fetch the desired one with the id() method provided by Mongoose. Then you can update its fields individually, or if you want to update multiple fields at once then use the set() method.
User.findById(userId)
.then((user) => {
const address = user.addresses.id(addressId); // returns a matching subdocument
address.set(req.body); // updates the address while keeping its schema
// address.zipCode = req.body.zipCode; // individual fields can be set directly
return user.save(); // saves document with subdocuments and triggers validation
})
.then((user) => {
res.send({ user });
})
.catch(e => res.status(400).send(e));
Note that you don't really need the userId to find the User document, you can get it by searching for the one that has an address subdocument that matches addressId as follows:
User.findOne({
'addresses._id': addressId,
})
// .then() ... the same as the example above
Remember that in MongoDB the subdocument is saved only when the parent document is saved.
Read more on the topic on the official documentation.
If you don't want separate collection, just embed the permissionSchema into the folderSchema.
var folderSchema = new Schema({
name: { type: string },
permissions: [ {
role: { type: String },
create_folders: { type: Boolean },
create_contents: { type: Boolean }
} ]
});
If you need separate collections, this is the best approach:
You could have a Permission model:
var mongoose = require('mongoose');
var PermissionSchema = new Schema({
role: { type: String },
create_folders: { type: Boolean },
create_contents: { type: Boolean }
});
module.exports = mongoose.model('Permission', PermissionSchema);
And a Folder model with a reference to the permission document.
You can reference another schema like this:
var mongoose = require('mongoose');
var FolderSchema = new Schema({
name: { type: string },
permissions: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Permission' } ]
});
module.exports = mongoose.model('Folder', FolderSchema);
And then call Folder.findOne().populate('permissions') to ask mongoose to populate the field permissions.
Now, the following:
savePermission: function (folderId, permission, callback) {
Folder.findOne({ _id: folderId }).populate('permissions').exec(function (err, data) {
var perm = _.findWhere(data.permissions, { _id: permission._id });
_.extend(perm, permission);
data.markModified("permissions");
data.save(callback);
});
}
The perm field will not be undefined (if the permission._id is actually in the permissions array), since it's been populated by Mongoose.
just try
let doc = await Folder.findOneAndUpdate(
{ "_id": folderId, "permissions._id": permission._id },
{ "permissions.$": permission},
);

Mongoose: Finding a user in a collection and checking if this user's array contains x?

I have a collection called 'users' where a typical user entry looks something like this:
{
"__v" : 0,
"_id" : ObjectId("536d1ac80bdc7e680f3436c0"),
"joinDate" : ISODate("2014-05-09T18:13:28.079Z"),
"lastActiveDate" : ISODate("2014-05-09T18:13:48.918Z"),
"lastSocketId" : null,
"password" : "Johndoe6",
"roles" : ['mod'], // I want this to be checked
"username" : "johndoe6"
}
I want to create an if function that finds a user variable targetuser, and checks to see if his 'roles' array contains a 'mod'.
How can this be done with mongoose?
It can be done easily. Code below describes in detail what must be done to achieve this.
Steps:
get mongoose module
connect to mongo and find the right database
make a schema of your collection (in this case only users)
add a custom method that returns true if the role 'mod' exists in the array. Note: mongo collection doesn't have structure, so it might be good to run a check if the property 'roles' exists and it is an array.
model the created schema.
test it by finding random (one) document/user and check if it is a moderator.
So, this is programmed as:
// get mongoose.
var mongoose = require('mongoose');
// connect to your local pc on database myDB.
mongoose.connect('mongodb://localhost:27017/myDB');
// your userschema.
var schema = new mongoose.Schema({
joinDate : {type:Date, default:Date.now},
lastActiveDate: Date,
lastSocketId : String,
username : String,
password : String,
roles : Array
});
// attach custom method.
schema.methods.isModerator = function() {
// if array roles has text 'mod' then it's true.
return (this.roles.indexOf('mod')>-1);
};
// model that schema giving the name 'users'.
var model = mongoose.model('users', schema);
// find any user.
model.findOne({}, function(err, user)
{
// if there are no errors and we found an user.
// log that result.
if (!err && user) console.log(user.isModerator());
});

How can I set composite primary key in mongodb through mongoose

I want to set primary key for two fields in a collection in mongodb through mongoose. I know to set composite primary key in mongodb as
db.yourcollection.ensureIndex( { fieldname1: 1, fieldname2: 1 }, { unique: true } )
but am using mongoose to handle mongodb I don't know how to set composite primary key from mongoose
update
I used mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true });
see my code
var mongoose = require('mongoose')
var uristring ='mongodb://localhost/fresh';
var mongoOptions = { db: { safe: true } };
// Connect to Database
mongoose.connect(uristring, mongoOptions, function (err, res) {
if (err) {
console.log ('ERROR connecting to: remote' + uristring + '. ' + err);
} else {
console.log ('Successfully connected to: remote' + uristring);
}
});
var mySchema = mongoose.Schema({
ColorScaleID:String,
UserName:String,
Range1:Number,
})
mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true });
var freshtime= mongoose.model("FreshTimeColorScaleInfo",mySchema)
var myVar = new freshtime({
ColorScaleID:'red',
UserName:'tab',
Range1:10
})
myVar.save()
mongoose.connection.close();
When I execute this code for first time I see a line {"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 } in mongodb's fresh database. When I execute the same code for second time I see two same lines.
{"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 }
{"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 }
If composite primary key worked then it shouldn't allow me to insert same data for second time. what would be the problem?
The way that you have defined your schema is correct and will work. What you are probably experiencing is that the database has already been created and that collection probably already exists even though it might be empty. Mongoose won't retro fit the index.
As an experiment, set your database to a DB that does not exist. e.g.:
var uristring ='mongodb://localhost/randomname';
and then try running those two lines against this database and see if you can still insert those two documents.
Then compare the contents of the "system.indexes" collection in each of those collections. You should see that the randomname db has the composite index correctly set.
As everybody mentioned, you got to use index method of a Schema to set composite unique key.
But this isn't enough, try restarting MongoDB after that.
May be you can try this in your mongoose schema model,
const AppSchema1 = new Schema({
_id :{appId:String, name:String},
name : String
});

Categories

Resources