How can i insert data to a schema array in nodejs? - node.js

I have a schema as shown below and I was trying to insert a value to that schema but data is not being assigned. How we can assign data to a schema array in nodejs?
building is my schema instance.
my schema is shown below
geoValues: [
{
latitude: Number,
longitude: Number,
}
],
I tried like below for assigning data to my schema
building. geoValues.latitude = latitude;
building. geoValues.longitude = longitude;

Check whether your mongoose schema looks like this,
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const buildingSchema = new Schema({
geoValues: [{
latitude: Number,
longitude: Number
}]
});

Related

How do I update the existing documents' schema?

I'm using mongoose to do some MongoDB operations.
At the beginning the category was number,
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const sampleSchema = new Schema({
category: {
type: Number,
}
})
module.exports = mongoose.model("SampleSchema", sampleSchema);
Now the category changed to String, So I changed the model like this
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const sampleSchema = new Schema({
category: {
type: String,
}
})
module.exports = mongoose.model("SampleSchema", sampleSchema);
The problem is, I have already inserted 200 records into this collection. Is there any way to update the category value with a string and change its type to string?
Please get All data by query and update it one by one in loop.
Like:
db.tableName.find( { 'status' : { $type : 1 } } ).forEach( function (val) {
val.status = new String(val.status);
db.tableName.save(val);
});
I changed the category to mixed, that's working fine with numbers and string.
Thanks for the help #prasad_

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 })

Nested Documents in Mongoose

I have two Mongoose schemas, User and Code. Each user can have many codes.
user.js:
var mongoose = require('mongoose');
var codeSchema = require('./code');
var userSchema = mongoose.Schema({
google: {
id: String,
token: String,
email: String,
name: String
},
codes: [codeSchema]
}, {collection : 'users'});
code.js:
var mongoose = require('mongoose');
var codeSchema = mongoose.Schema({
code: String,
name: String,
link: String
}, {collection: 'codes'});
module.exports = codeSchema;
My problem is, whenever I access a user's array of codes by user.codes, I get something like { _id: 56c4c82a37273dc2b756a0ce },{ _id: 56c4c82a37273dc2b756a0cd } rather than the JSON for a code.
What am I missing?
You're missing populate.
By default, Mongoose will only give you the _ids of any references made in a document. populate allows you to fill out nested documents.
userSchema.findOne({}).populate('codes');
More here
please check that you are inserting other values or not this can be a case . Please write how you are inserting in array . I have two other way check out
There are two way to do this
1-->either you save refrence id of codeschema and
2--> is you can insert whole codeschema in array
1. codes: {
type: mongooseSchema.ObjectId,
ref: 'codeSchema',
required: true
},
and when all data is in array 56c4c82a37273dc2b756a0ce,56c4c82a37273dc2b756a0cd
that can be done by this query
domain.User.update({_id:id}
,{$addToSet:{code:codeObjvalue}},
function(err,res){});
and then populate them by this
domain.users.find({},'code')
.populate('code','code color email').
exec(function(err,results){
callback(err, results);
});
2-- and second is to insert whole code schema in userschema
create a codeschema object and add in set like this
var codeobj={};
codeobj.code="xyz";
codeobj.email="xyz#gmail.com"
var codeobject = new domain.code(codeobj);
domain.User.update({_id:id},{$addToSet:{code:codeobject}},function(err,user1){
});
Woops, turns out I was using the wrong dataset, not adding the codes properly (facepalm). Thanks to everyone who answered!

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 Sub-documents on separate files, how to embed them

I'm defining my application models and i have separate files for each model that i'm defining, my question is, i need to create a model that use a sub-document, but that's on another file, how can i use that Schema on my model ? what i mean is that all examples i've seen declare the Child model and the Parent on the same file, example:
var childSchema = new Schema({ name: 'string' });
var parentSchema = new Schema({
children: [childSchema]
});
I have one file called user.js that defines the user model :
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
_id : Schema.Types.ObjectId,
username : String,
});
module.exports = mongoose.model( 'User', userSchema );
And on another file called sport.js i have the other model definition for the sports:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var sportSchema = new Schema({
_id : Schema.Types.ObjectId,
name : String
});
module.exports = mongoose.model( 'Sport', sportSchema );
So on my user model I need to define a field for the sports that the user will follow, but i do not know how to define that sub-document since the sports definition is on another file, I tried this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SportsModel = require('sport');
var userSchema = new Schema({
_id : Schema.Types.ObjectId,
username : String,
sports : [SportsModel]
});
module.exports = mongoose.model( 'User', userSchema );
But i'm not sure if that's the correct way since what i'm exporting is the model, not the Schema.
Thanks in advance, i want to define each model on separate files to maintain order.
You can access a Model's schema via its schema property. So this should work:
var userSchema = new Schema({
_id : Schema.Types.ObjectId,
username : String,
sports : [SportsModel.schema]
});
Use ref
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
_id : Schema.Types.ObjectId,
username: String,
sports : [{ type: Schema.Types.ObjectId, ref: 'Sport' }]
});
module.exports = mongoose.model('User', userSchema);
Incidentally, with ref, you can use .populate('sports') when you query, and mongoose will expand those types for you.

Resources