How to save nested mongoDB properties with mongoose? - javascript

Let say that i want to make a user schema with nested properties:
var userSchema = new mongoose.Schema({
username: { type: String, unique: true, lowercase: true },
/* ... some other properties ... */
profile: {
firstName: { type: String, default: '' },
/* ... some other properties ... */
},
});
module.exports = mongoose.model('User', userSchema);
Now if i want to save a user in a nodejs framework like ExpressJs, i will save it like so:
var user = new User({
username: req.body.username,
profile.firstName: req.body.firstName /* this is what i want to achive here */
});
user.save(function(err) {
if (!err) {
console.log('User created');
}
});
And i want to know if my Schema is good, or it's best practice to make all the properties in the root, as this:
var userSchema = new mongoose.Schema({
username: { type: String, unique: true, lowercase: true },
firstName: { type: String },
/* ... some other properties ... */
},
});

Your schema is good, but you cant define nested properties on the root of a new object as you did in your second code sample without quoting them. It should look like this:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var User = mongoose.model('User', {
username: String,
profile: {
firstName: String
}
});
var user1 = new User(
{
username: 'Zildjian',
'profile.firstName':'test'
});
user1.save(function (err) {
if (err) // ...
console.log('meow');
process.exit(0);
});
Although I would recommend nesting it properly like this
var user1 = new User(
{
username: 'Zildjian',
profile: {
firstName:'test'
}
});

Related

Reference another Schema in Mongoose

so I have to Schemas. PostSchema and UserSchema
const mongoose = require("mongoose")
const PostSchema = new mongoose.Schema({
content: {
type: String,
required: true,
},
likes: {
type: Number,
required: true
},
rescreams: {
type: Number,
required: true
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
createdAt: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model("Post", PostSchema)
UserSchema:
const bcrypt = require("bcrypt");
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
userName: { type: String, unique: true },
email: { type: String, unique: true },
password: String,
});
// Password hash middleware.
UserSchema.pre("save", function save(next) {
const user = this;
if (!user.isModified("password")) {
return next();
}
bcrypt.genSalt(10, (err, salt) => {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, (err, hash) => {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
});
// Helper method for validating user's password.
UserSchema.methods.comparePassword = function comparePassword(
candidatePassword,
cb
) {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
cb(err, isMatch);
});
};
module.exports = mongoose.model("User", UserSchema);
My question is: I'm trying to reference the User Object ID in the Post Schema. As you can see, I've done that with type: mongoose.Schema.Types.ObjectID. And I've seen this multiple times. But in my database, the User never shows up in the Document. What do I need to do?
Cheers
There is a difference between referencing a document and embedding a document.
If you want to store a document inside a document you should embed it, thus read operations will be faster because you won't need to perform JOIN operations.
Whereas referencing means storing an ID of an entity that you are referencing, when you need to access the document you are referencing, you need to fetch it from the collection by the ID you have stored. It is slower than embedding, but it gives you higher consistency and data integrity because the data is stored once at the collection and not duplicated at every object. And MongoDB does not support foreign keys so you should be careful with referencing.
So when you are storing the document using ref, you need to put an ObjectID as a user and then fetch the document you need to add populate call. e.g.
PostShema.findOne({ _id: SomeId }).populate('user');
try to save in a variable:
const UserId = UserSchema.Schema.Types.ObjectId;
for more information:
https://mongoosejs.com/docs/api/schema.html#schema_Schema.Types

how to save data to mongodb schema with object

I've been trying to save user data to a mongodb schema, sample schema below, the question is how can i insert data inside the object. Please help i've been doing this for hours
e.g. User.js
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
data:{
type: String,
requred: true
},
data2:{
type: String,
requred: true
},
work: {
industry: String,
name: String,
position: String,
},
status:{
type: Boolean,
default: true,
requred: true
},
subscription:{
product: String,
license: String,
price: String,
status: Boolean,
default: false,
renew: Boolean,
default : false
},
date:{
type: Date,
default: Date.now
}
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
sample registration handling
const newUser = new User({
data1,
data2,
work,
subscription
});
newUser.save()
.then(user => {
req.flash('success_mg', 'Successfully Registered your can now Login.');
res.redirect('/login');
})
.catch(err => console.log(err));
You want to use the _id field, and call your schema like this:
User.findByIdAndUpdate({_id: id}, {...updates}, {new: true})
.then(updated_user=>{ DO SOMETHING... })
the ...updates would be a JSON object containing the keys and values of the properties you're updating.

MongoDB Unable to push to array with findOneAndUpdate()

Been working on a project recently where users subscribe to a class... however I am having trouble with pushing the class to the array... here is my code
const userSchema = new mongoose.Schema({
email: String,
password: String,
secret: String,
classes: [String]
});
const userModel = mongoose.model("Class", userSchema)
app.post("/subscribe", function (req, res) {
const newClass = req.body.subClass;
const id = req.user.id
const ObjectId = mongoose.Types.ObjectId;
userModel.findOneAndUpdate(
{ _id: new ObjectId(id) },
{ $addToSet: { letters: [newClass] } },
{ upsert: false }
);
});
I skipped through the program for useful info so please comment if more code is needed... looking to finally finish this up!

mongoose save to 2 collection

Hello guys i really need help for this one . It's been bugging me for how many days
model/user.js
var UserSchema = mongoose.Schema({
username:{
type: String,
unique: true,
index:true
},
password:{
type:String
},
email:{
type:String,
required: true
// unique: true
},
authToken:{
type: String,
required: true,
unique: true
},
IsAuthenticated:{
type: Boolean,
required: true
},
name:{
type:String
},
field:{
type:String
},
e_money:{
type:Number //this is the integer form in mongoose
}
});
//accesible variable from the outside
var User = module.exports = mongoose.model('users', UserSchema);
var InfoUser = module.exports = mongoose.model('infouser', UserSchema);
and how i save is like this
var User = require('../models/user);
var newUser = new User({
name: name,
email: email,
authToken: authToken,
IsAuthenticated: false,
username: username,
password: password,
field: field,
e_money: e_money //temporary emoney
});
var newUser2 = new InfoUser({
name: name,
email: email,
authToken: authToken,
IsAuthenticated: false,
username: username,
password: password,
field: field,
e_money: e_money //temporary emoney
});
//save the newly created user to database
User.createUser(newUser,function(err, user){
if(err) throw err;
console.log(user);
)};
User.createUser(newUser2,function(err,user){
if(err) throw err;
console.log(user);
)};
What is the problem it always says that the infouser is not defined. Can someone plase
The problem is that you are exporting two different models through the same module.exports. Instead I would recommend that you export them separately:
model/user.js
// You can add instance methods like this:
UserSchema.methods.createUser = function(user) {
// Whatever you want to do here
};
var User = mongoose.model('users', UserSchema);
var InfoUser = mongoose.model('infouser', UserSchema);
exports.User = User;
exports.InfoUser = InfoUser;
/*
You could also do this as:
module.exports = { User: User, InfoUser: InfoUser };
*/
Then when you want to use them:
var User = require('../models/user').User;
var InfoUser = require('../models/user').InfoUser;

How to get data from mongoose model and store with variable like mvc using node.js

Here below code is sample MVC framework code in PHP. I need same process as like in node.js with mongoose also.
I'm using Node.js, MongoDB, REST API development.
controller file:
<?php
class Myclass {
public function store_users() {
//get the data from model file
$country = $this->country->get_country_details($country_id);
//After getting data do business logic
}
}
model file
<?php
class Mymodel {
public function get_country_details($cid) {
$details = $this->db->table('country')->where('country_id',$id);
return $details;
}
}
In node.js need to use as like MVC PHP process. Kindly suggest on this.
Lets say you have user schema in mongoose which should act as model
// userModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var user = new Schema({
name: { type: String, required: true },
dob: { type: Date },
email: { type: String, required: true, unique: true, lowercase: true},
active: { type: Boolean, required: true, default: true}
}, {
timestamps: {
createdAt: 'created_at',
updatedAt: 'updated_at'
}
});
var userSchema = mongoose.model('users', user);
module.exports = userSchema;
// userController.js
var User = require('./userModel');
exports.getUserByEmail = function(req, res, next) {
var email = req.param.email;
User.findOne({ email: email }, function(err, data) {
if (err) {
next.ifError(err);
}
res.send({
status: true,
data: data
});
return next();
});
};
Ref: http://mongoosejs.com/docs/index.html

Categories