how to use the value of an item in a mongoose schema - node.js

I want to get the value of item in a schema and use it in the same schema.
e.g Have a
const mongoose = require("mongoose");
const TestSchema = new mongoose.Schema({
appellant: String,
respondent: String,
title: `${this.appellant} V. ${this.respondent}`,
});
module.exports = mongoose.model("Test", TestSchema);

Usually, a virtual schema is used for instances such as this. It allows you to utilize the data in a particular format, without persisting it and creating redundant data.
In your case, it would look something like this:
TestSchema.virtual('title').get(function () {
return this.appellant + ' V. ' + this.respondent
});

Related

Mongoose $pull not removing embedded sub-document by ObjectId [duplicate]

Is there a function to turn a string into an objectId in node using mongoose? The schema specifies that something is an ObjectId, but when it is saved from a string, mongo tells me it is still just a string. The _id of the object, for instance, is displayed as objectId("blah").
You can do it like so:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');
You can use this also
const { ObjectId } = require('mongodb');
const _id = ObjectId("4eb6e7e7e9b7f4194e000001");
it's simplest way to do it
You can do it like this:
var mongoose = require('mongoose');
var _id = mongoose.mongo.BSONPure.ObjectID.fromHexString("4eb6e7e7e9b7f4194e000001");
EDIT: New standard has fromHexString rather than fromString
Judging from the comments, you are looking for:
mongoose.mongo.BSONPure.ObjectID.isValid
Or
mongoose.Types.ObjectId.isValid
var mongoose = require('mongoose');
var _id = mongoose.mongo.ObjectId("4eb6e7e7e9b7f4194e000001");
I couldn't resolve this method (admittedly I didn't search for long)
mongoose.mongo.BSONPure.ObjectID.fromHexString
If your schema expects the property to be of type ObjectId, the conversion is implicit, at least this seems to be the case in 4.7.8.
You could use something like this however, which gives a bit more flex:
function toObjectId(ids) {
if (ids.constructor === Array) {
return ids.map(mongoose.Types.ObjectId);
}
return mongoose.Types.ObjectId(ids);
}
Just see the below code snippet if you are implementing a REST API through express and mongoose. (Example for ADD)
....
exports.AddSomething = (req,res,next) =>{
const newSomething = new SomeEntity({
_id:new mongoose.Types.ObjectId(), //its very own ID
somethingName:req.body.somethingName,
theForeignKey: mongoose.Types.ObjectId(req.body.theForeignKey)// if you want to pass an object ID
})
}
...
Hope it Helps
If you want to use schema
const yourSchemma = new Schema({
"customerId": {
type: mongoose.Types.ObjectId,
required: true
}
});
If you want to use ObjectId a lot and don`t want to use mongoose.types.ObjectId, you can destructure your declaration:
const {
Types: { ObjectId: ObjectId },
} = require("mongoose");
const id=ObjectId("4edd40c86762e0fb12000003")

Mongoose Schema in node js

Mongo Database
I want to create the data model(Schema) in node js according to the the database shown in the picture. How to create the data model of array in node js and also the inside the array which have object, which also contain another array?
const mongoose = require('mongoose');
mongoose.pluralize(null);
const Schema = mongoose.Schema;
const indicatorsSchema = new Schema({
name:String,
metrics:[String] //[String] define array of string
}, { _id: false });
const Learning = new Schema({
learningEvents: String,
learningActivities: [String], //[String] define array of string
indicators:[indicatorsSchema] // define object as above
}, { versionKey: false })

Dynamic schema keys in Mongoose

I have a simple requirement to get dynamic keys and their values to insert in mongo.
something like this:
[
{"key1": "val1"},
{"key2": "val2"}
]
For this I have created schema as :
As I read about [Schema.Types.Mixed],but it only makes datatype of assigned values dynamic ,not the key in my case.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var myschema = new Schema({ key: [Schema.Types.Mixed] });
module.exports = mongoose.model('DataCollection', myschema);
Can anybody point , whtat is it that I am missing.
This is my output,which shows blank value.
Thanks in advance.
I don't think it is possible to literally have a dynamic key as that defeats the purpose of a schema, but you could do something like this:
var KeyValueSchema = new Schema({
key : String,
value : String
});
module.exports = mongoose.model('KeyValueCollection', KeyValueSchema);
Alternatively using the Mixed data type you could store an entire JSON object. For example using this schema:
var mySchema = new Schema({
data : Schema.Types.Mixed
});
module.exports = mongoose.model('DataCollection', mySchema);
You could insert like:
.post(function(req, res) {
var collection = new DataCollection();
collection.data = {'key' : 'value'};
collection.save(function(err) {
if(err) res.send(err);
res.json({message:'Data saved to collection.'});
});
});

How to define a nested schema in mongoose?

My mongo record is like this:
{
"_id":{"$oid":"5550b6de437f572112a29f1a"},
"cv_count":177732,
"gender_info": {"male_count": 50, "female_count": 32}
"stability_info_list":[{"ratio":8.802558610369414e-05,"total_count":34081,"years":0},{"ratio":5.868372406912943e-05,"total_count":34081,"years":1}],
"zhineng_id":"IT Manager"
}
I write the schema like this:
var ZhinengGenderSchema = new Schema({
male_count: Number,
female_count: Number
});
var ZhinengStabilitySchema = new Schema({
ratio: Number,
total_count: Number,
years: Number
});
var ZhinengStats = new Schema({
cv_count: Number,
gender_info: ZhinengGenderSchema,
stability_info_list: [ZhinengStabilitySchema],
zhineng_id: String
})
But I got this excetion:
TypeError: Undefined type `undefined` at `gender_info`
Did you try nesting Schemas? You can only nest using refs or arrays.
so mongoose doesn't support nest schemas? But my database has already been there, I cannot change, so how can I define my schema?
Just don't create a new schema for the subdocuments and you should be fine, i.e.:
var ZhinengGenderSchema = {
male_count: Number,
female_count: Number
};
var ZhinengStabilitySchema = {
ratio: Number,
total_count: Number
years: Number
};
var ZhinengStats = new Schema({
cv_count: Number,
gender_info: ZhinengGenderSchema,
stability_info_list: [ZhinengStabilitySchema],
zhineng_id: String
})
With mongoose you can define nesting (embedded) schemas in Array, like this:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var bookSchema = new Schema({
value: { type: String }
});
var authorSchema = new Schema({
books: [bookSchema]
});
Or by reference
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = mongoose.Schema.Types.ObjectId;
var auhtorSchema = new Schema({
book: { type: ObjectId, ref: 'Book'}
});
You may choose what is more appropriate for you
As far as I know, this is due to a current limitation of Mongoose. You cannot
declare a schema field to include a single sub-document: you have to use an array, instead. See this: https://github.com/Automattic/mongoose/pull/585
You can set up later the proper business logic in order to ensure that only one sub-element will be added.
Try this:
var ZhinengStats = new Schema({
cv_count: Number,
gender_info: [ZhinengGenderSchema],
stability_info_list: [ZhinengStabilitySchema],
zhineng_id: String
})
This way, each sub-document has got its own _id in MongoDB (even though it does not lie in a specific collection). See more: http://mongoosejs.com/docs/subdocs.html
You could also prefer something like this:
var ZhinengStats = new Schema({
cv_count: Number,
gender_info: [{male_count: Number, female_count: Number}],
stability_info_list: [ZhinengStabilitySchema],
zhineng_id: String
})
In this case, you nest a schema inside another. The single gender_info element does not have the dignity of a document.

Mongoose: Generate Schema from existing data

For example, I have user collection in db:
{'_id':0, 'name': 'Joe', 'score':[80, 33]}
{'_id':1, 'name': 'Moe', 'score':[90, 81]}
... ...
How can I read this data with existing format, which means, use it's existing schema without create a new one.
I read Mongoose doc and googled for a while but didn't find satisfied answer.
When using mongoose with an existing collection, you have to reference the collection in your mongoose schema. The way to do this is to add the name of the collection to your schema. So if your collection is in 'mongodb://localhost:27017/test' and called 'things', you would use:
~~~
const Schema = mongoose.Schema;
const ThingSchema = new Schema({
name: {
type: String
}
});
const Model = mongoose.model('Thing', ThingSchema, 'things');
module.exports = Model;
~~~
Thanks to http://chrisflx.blogspot.fr/2014/04/nodejs-mongoose-with-preexisting-data.html?m=1
It will work if you make a model with the same schema.
var schema = new mongoose.Schema({ name: 'string', score: [] });
var user = mongoose.model('User', schema);
Edit:
Mongoose is an ODM, so you need a schema to create objects. If you need to run queries and get raw data from the database, I would stick with this library:
https://github.com/mongodb/node-mongodb-native

Resources