Why mongoose schema type is double, but when insert value, type in mongo is int32? - mongodb

I'm using mongoose-double to define Double type for mongoose.
My schema contain values property is an array of Double.
In pre-save middleware, init values is an array with 6 items 1000.
Check in mongo, 1000 type is int32
const mongoose = require('mongoose');
require('mongoose-double')(mongoose);
const Double = mongoose.Schema.Types.Double;
const test = new mongoose.Schema({
values: [Double]
})
test.pre('save', function(next) {
this.values = new Array(6).fill(1000),
})
I did what wrong ?

Well, in my opinion, you don't need to use Double.
As far as I know, there is 'Number' type in mongoose schema and it can be double, number and etc.
So use Number instead of Double.
const test = new mongoose.Schema({
values:Number
})
but in your case, you should use like this.
const test = new mongoose.Schema({
values:[Number]
})

Related

Query related to Mongoose document and mongodb

In the code below after adding bananna document to my database, i m assigning it to new person as an entry,
i want to know that how can i pass this banana document from the database to my new person.
const personSchema = new mongoose.Schema({
name:String,
age:Number,
favourate_fruit: fruitSchema
});
const Fruit = mongoose.model("Fruit",fruitSchema);
//persons
const Person = mongoose.model("Person",personSchema);
const bananna = new Fruit({name:"bananna",rating:4,review:"Just ok"});
Person.updateOne({name:"Ankit"},{favourate_fruit:bananna},(err)=>{
console.log("Updated record added new ");
})

How can I transform an object schema's property schemas to derive a new object schema?

Is there a way to introspect and then transform a Joi schema?
I see there is any.describe() which "returns an object that represents the internal configuration of the schema" but then I have to map that internal configuration back to schema builder calls and re-create the schema myself.
e.g. given
const PersonSchema = Joi.object().keys({
firstName: Joi.string().required(),
lastName: Joi.string().required(),
age: Joi.number().required(),
});
I want to define a generic function to take any object schema and make its properties support arrays of the original type equivalent to the following:
const PersonFilterSchema = Joi.object().keys({
firstName: Joi.array().items(Joi.string().required()).optional(),
lastName: Joi.array().items(Joi.string().required()).optional(),
age: Joi.array().items(Joi.number().required()).optional(),
});
i.e. I want to be able to write something like this:
function createFilterSchema(schema) {
return Joi.object().keys(
Object.fromEntries(
schema
.getEntries()
.map(([key, value]) => [key, Joi.array().items(value).optional()])
)
);
}
and then elsewhere use it with whatever raw schemas I have:
const PersonFilterSchema = createFilterSchema(PersonSchema);

How do you set-up a mongoose column from schema A to have the values from a column from schema B?

I have
schema A:
let informationAssetsRow = new Schema({
infAss: {
type: String
})
Schema B
let informationAssetsSeverityEvaluationRow = new Schema({
Informationasset: {
type: String
}
})
For the sake of simplicity I have removed other attributes.
What I would like to do is:
Each time a document inserted in collection A. I want the value of infAss to be also inserted in Informationasset in column B.
From SQL perspective, this seems to be infAss of collection A should be set-up as an external key to schema B. I'm not sure I'm right.
However, in mongodb it's not clear if that is doable.
Any help?
You can create a post('save') hook on informationAssetsRow schema to achieve what you want.
Everytime a new document is inserted in collection A, post save hook will save new document into collection B.
Try this:
informationAssetsRow.post('save',function(doc){
informationAssetsSeverityEvaluationRow.create({
Informationasset : doc.infAss
})
})
Read more about Mongoose Post Hooks for detailed information.

Mongoose - how to use model inheritance in a sub document collection

I have this model setup. I want a parent record with an array of sub docs.
The sub docs have a schema, and use inheritance.
//
// Children
function abstractSchema() {
Schema.apply(this, arguments);
this.add({
name: String
});
};
util.inherits(abstractSchema, Schema);
var mySchema = new abstractSchema();
//
// Inherited Types
var textPropertySchema = new abstractSchema({
length: Number
});
var numberPropertySchema = new abstractSchema({
dp: Number
});
//
// Parent Model
var myModelSchema = mongoose.Schema({
name: String,
properties : [mySchema]
});
When i save each an instance of numberPropertySchema or textPropertySchema, the _t (type is written) and is able to deserialise properly.
When however added as a sub doc array, they're all persisted with the base object properties only.
Is there any way round this? any extensions that could be used?
Thanks
sam

Mongoose -- Force collection name

I am trying to use mongoose to create a database and a collection in it. My code is:
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/testdb');
var Schema = mongoose.Schema;
var UserInfo = new Schema({
username : String,
password : String
});
mongoose.model('UserInfo', UserInfo);
var user = db.model('UserInfo');
var admin = new user();
admin.username = "sss";
admin.password = "ee";
admin.save();
When I run this code, mongoose created collection named UserInfo instead of userinfo.
How to force collection name in mongoose?
This should do it
var UserInfo = new Schema({
username : String,
password : String
}, { collection: 'userinfo' });
See this link from the Mongoose documentation for more information.
If you are using mongoose 2.0.0, pass the collectionName as the third argument
mongoose.model('UserInfo', UserInfo, 'UserInfo');
Mongoose will add 's' to collection name by default. If you want to avoid that, just pass as third argument the name of the collection:
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/testdb');
var Schema = mongoose.Schema;
var UserInfo = new Schema({
username: String,
password: String
});
mongoose.model('UserInfo', UserInfo, 'UserInfo')
tan = new user();
admin.username = 'sss';
admin.password = 'ee';
admin.save();
API structure of mongoose.model is this:
Mongoose#model(name, [schema], [collection], [skipInit])
What mongoose do is that, When no collection argument is passed, Mongoose produces a collection name by pluralizing the model name. If you don't like this behavior, either pass a collection name or set your schemas collection name option.
Example:
var schema = new Schema({ name: String }, { collection: 'actor' });
or
schema.set('collection', 'actor');
or
var collectionName = 'actor'
var M = mongoose.model('Actor', schema, collectionName);
You need to set the collection name in your schema.
new Schema({...},{collection: 'userInfo'});
Mongoose maintainer here. We recommend doing mongoose.model('UserInfo', UserInfo, 'UserInfo');, third arg to mongoose.model() is the collection name. Here's the relevant docs.
Passing a third argument on module.exports = mongoose.model('name', schema, 'collection') overrides the automatic collection name based on model name, which has already been answered.. but there are 2 other ways,
per mongoose.model doco link:
https://mongoosejs.com/docs/api.html#mongoose_Mongoose-model
there are 3 methods to manually enter a collection name:
var schema = new Schema({ name: String }, { collection: 'actor' });
// or
schema.set('collection', 'actor');
// or
var collectionName = 'actor'
var M = mongoose.model('Actor', schema, collectionName)
Answer:
mongoose.model('UserInfo', UserInfo, 'userinfo'); //3rd parameter 'userinfo': as collection name
Better explanation with syntax:
Mongoose.model(name, [schema], [collection], [skipInit])
Parameters Explanation:
1st parameter - name model name
2nd parameter [schema] schema name
3rd parameter [collection] collection name (optional, induced from model name)
4th parameter [skipInit] whether to skip initialization (defaults to false)
your model name : userInfo.js
in express route file or app.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/testdb');
then in your userInfo.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserInfo = new Schema({
username : String,
password : String
});
module.exports = mongoose.model('UserInfo', UserInfo);