I reuse a project About Node and Passport that use mongodb, where a schema is defined as the following, in a user.js file
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
local : {
email : String,
password : String,
},
facebook : {
id : String,
token : String,
email : String,
name : String
},
twitter : {
id : String,
token : String,
displayName : String,
username : String
},
google : {
id : String,
token : String,
email : String,
name : String
}
});
module.exports = ('User', userSchema);
As i'm using mysql, I'm trying to keep that object structure, for the rest of the code.
So how can I define an object like this, to be able to instantiate it, to then work on it like :
var User = require('../app/models/user');
var newUser = new User();
newUser.local.email = "babab";
newUser.local.password = "bababab";
Probably a trival question, but I'm a bit lost with the javascript object handling.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
What you're looking for is javascript prototypes
edit: here's an article for node specifically,
http://howtonode.org/prototypical-inheritance
Following #kirinthos, various solution appears. I select the most basic one (I think), but comment and improvement are welcome:
The object definition
module.exports = Object({
id : String,
local : {
email : String,
password : String,
},
facebook : {
id : String,
token : String,
email : String,
name : String
},
twitter : {
id : String,
token : String,
displayName : String,
username : String
},
google : {
id : String,
token : String,
email : String,
name : String
}
});
The object instancitation :
var User = require('../app/models/user');
var newUser = Object.create(User);
newUser.local.email = "babab";
newUser.local.password = "bababab";
Related
When I retrieve and modify a Lobby with this Schema it seems to automatically cast types. I could not find the documentation for that feature so I am wondering if I am mistaken something else for autocasting.
I convert the types of password and owner to true or false because this is an exposed API endpoint everyone can view.
When I run the anonymizer function it runs and results in password : "true" not password: true. I would like it to send password: true but I am not sure if that is possible.
// Schema
const LobbySchema = new mongoose.Schema({
name: String,
password: String,
owner: { type: String, require: true },
Player: [],
});
// Anonymizer function
lobby.password = !!lobby.password;
lobby.owner = lobby.owner === user ? true: false;
res.send(JSON.stringify(lobby));
Yes, Mongoose cast values if it is possible.
The problem here is your schema define type owner as String. So the value true or false will be casted to string.
This is why you get password : "true".
To get password as a boolean you can either set Boolean into the schema or use Custom casting
Not tested but following the documentation should be similar to this:
const originalCast = mongoose.Boolean.cast();
mongoose.Boolean.cast(v => {
if (v === 'true') {
return true;
}
if (v === 'false') {
return false;
}
return originalCast(v);
});
How to save .text of commentSchema as array format in the field of .comments in reviewSchema?
of course each review (post) has multiple comments.
// Connect to the db using mongoose
mongoose.connect("mongodb://localhost:27017/reviewdb")
// setting up model and schema for comment
var commentSchema = new mongoose.Schema( {
text: String,
user : String,
username: String,
date: Date
});
// setting up model and schema for reviews
var reviewSchema = new mongoose.Schema( {
text: String,
user : String,
username: String,
mydate: Date,
likes:{type: Number, "default":0, min:0},
comments:[commentSchema]
});
// setting up model for review
var Review = mongoose.model('review', reviewSchema);
// setting up model for comment
var comment = mongoose.model('comment', reviewSchema);
I´m using mongoose and I need to find a model name from a model instance.
In one part of the code I have:
const schema = new mongoose.Schema({
name: {
type: String,
required: true
},
phone: {
type: String,
required: true
}
}
const schema = new mongoose.Schema('MyData', schema);
let instance = new this({
name: 'Pete',
phone: '123'
});
Ths instance variable is passed around in my code. Later I need to find out instance name, but I´m no sure if there is a way to do it, something like:
let instanceName = getInstanceName(instance); <== Expects 'MyData' to be returned
Is that possible using mongoose ?
I realized I had a model not an instance of a model so I needed to use something else.
If you have a model, you can get the name as below:
const model = mongoose.model("TestModel", schema);
const collectionName = model.collection.collectionName;
If you have a specific item/instance of the model:
const instance = new model({...});
const collectionName = instance.constructor.modelName
as Hannah posted.
The name of the model can be accessed using this instance.constructor.modelName.
In my case I was looking for how to get a discriminator model name from a mongoose model, and the suggested solutions didn't work:
const PerformanceResult = DropDown.discriminator('PerformanceResult', new db.Schema({
name: { type: String, required: true }
}))
export default PerformanceResult
console.log(PerformanceResult.constructor.modelName) // undefined
console.log(PerformanceResult.collection.collectionName) // DropDown (parent name)
you can use this:
console.log(PerformanceResult.modelName) // PerformanceResult
mongoose version: "^5.11.8"
I guess it's a stupid question but i would like do something like this
var mongoose = require('mongoose');
var Long = require("long");
var UserSchema = new mongoose.Schema({
id: Long(),
name: String,
completed: Long(),
note: String,
updated_at: { type: Date, default: Date.now },
});
But it's not working,"cannot set 'low' property". I know that cause I do not pass arguments in the "Long" constructor but it's not working iven if I don't put the "()". I'm a bit lost with that ^^'
Sorry for my english ^^'
You should use a module specifically designed for Mongoose, like mongoose-long:
var mongoose = require('mongoose')
require('mongoose-long')(mongoose);
var Long = mongoose.Schema.Types.Long;
var UserSchema = new mongoose.Schema({
id : Long,
name : String,
completed : Long,
note : String,
updated_at : { type: Date, default: Date.now },
});
I have a node.js api built out that updates a subdocument. Below is the post call for the subdocument:
.put(function(req, res) {
member.findById(req.params.member_id, function(err, member) {
if (err)
res.send(err);
console.log("old: " + member);
member.address[req.params.address_id].address_type = req.body.address_type;
member.address[req.params.address_id].street1 = req.body.street1;
member.address[req.params.address_id].street2 = req.body.street2;
member.address[req.params.address_id].City = req.body.City;
member.address[req.params.address_id].State = req.body.State;
member.address[req.params.address_id].Zip = req.body.Zip;
member.address[req.params.address_id].Lat = req.body.Lat;
member.address[req.params.address_id].Lng = req.body.Lng;
console.log("new: " + member);
member.save(function(err) {
if (err)
res.send(err);
res.json({message:'Address Updated!!!'});
})
})
})
The two console.log lines prove that the object was found in the findById call, then updated after going through the array. The logs prove that the object in memory is in fact updated.
However, when actioning the .save() call, I get the success message, but nothing changes in mongodb.
I get no errors, no warnings, nothing. It says success, but no change.
How do I troubleshoot?
here's my Address Model:
var mongoose = require('mongoose'),
Schema = mongoose.Schema
var AddressSchema = Schema({
Address_type : String,
street1 : String,
street2 : String,
City : String,
State : String,
Zip : Number,
Lat : Number,
Lng : Number
});
module.exports = mongoose.model('Address', AddressSchema);
and here's the parent model, member:
var mongoose = require('mongoose'),
Schema = mongoose.Schema
var Address = require('./address');
var Award = require('./award');
var MemberSchema = Schema({
FName : String,
LName : String,
address: [Address.Schema],
phone : {
type : String,
number : String
},
email: String,
gender: String,
DOB: Date,
rank : {
level : String,
updated: { type: Date, default: Date.now }
},
Awards : {
personal : Boolean,
award : [Award.Schema],
granted: { type: Date, default: Date.now }
}
});
module.exports = mongoose.model('Member', MemberSchema);
When you update an array element of a Mongoose document via its index it doesn't trigger the change detection of the array so Mongoose doesn't know to save it (see the FAQ).
To manually trigger the change detection, you can call markModified before your call to member.save:
member.markModified('address');
To help troubleshoot these types of problems, enable Mongoose's debug output to see the actual calls it's making to the native driver by adding the following to your startup code:
mongoose.set('debug', true);