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.
Related
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
I'm new to Express/Mongoose and backend development. I am attempting to use a Mongoose subdocument in my Schema and POST data from a form to an MLab database.
I am successfully POSTing to the database when only using the parent Schema, but when I attempt to also POST data from the subdocument I am getting an undefined error. How do I properly POST data from a subdocument?
Here is my Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bookSchema = new Schema({
bookTitle: {
type: String,
required: true
},
author: {
type: String,
required: true
},
genre: {
type: String
}
});
const userSchema = new Schema({
name: String,
username: String,
githubID: String,
profileUrl: String,
avatar: String,
// I've tried this with bookSchema inside array brackets and also
//without brackets, neither works
books: [bookSchema]
});
const User = mongoose.model('user', userSchema);
module.exports = User;
Here is my route where I attempt to POST to the database:
router.post('/', urlencodedParser, (req, res) => {
console.log(req.body);
const newUser = new User({
name: req.body.name,
username: req.body.username,
githubID: req.body.githubID,
profileUrl: req.body.profileUrl,
avatar: req.body.avatar,
books: {
// All of these nested objects in the subdocument are undefined.
//How do I properly access the subdocument objects?
bookTitle: req.body.books.bookTitle,
author: req.body.books.author,
genre: req.body.books.genre
}
});
newUser.save()
.then(data => {
res.json(data)
})
.catch(err => {
res.send("Error posting to DB")
});
});
Figured it out. I wasn't properly accessing the values using dot notation.
books: {
// All of these nested objects in the subdocument are undefined.
//How do I properly access the subdocument objects?
bookTitle: req.body.books.bookTitle,
author: req.body.books.author,
genre: req.body.books.genre
}
No need to access .books inside of the books object. req.body.books.bookTitle should be req.body.bookTitle and so forth. Leaving this post up in case it helps someone else.
I m trying to use populate( ) in node js.
Well I m trying to access, objectId of one collection into another collection.
for eg., i have collections called Project and events,
where i have schema like this.
Project schema:
const projectSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
projectName: {
type: String,
required: true,
unique: true
},
dimensions: {
type: [],
required: false
},
events: {
[type: mongoose.Schema.Types.ObjectId],
ref: 'EnrichedEvent'
},
});
module.exports = mongoose.model('Project', projectSchema);
Events Schema:
const enrichedEventSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
projectId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Project',
required: true
},
name: {
type: String,
required: true
},
type: {
type: String,
enum: ["Enriched"],
required: true
},
source: {
type: String,
required: true
},
});
and the routing code for projects to :
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const Project = require("../models/project");
router.get("/", (req, res, next) => {
Project.find()
.populate('source', 'EnrichedEvents') //When i use this populate method, I m not able to GET any events on to browser..
.exec()
.then(docs => {
const response = {
count: docs.length,
projects: docs.map(doc => {
return {
projectName: doc.projectName,
dimensions: doc.dimensions,
events: doc.events,
_id: doc._id
};
})
};
res.status(200).json(response);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
router.post("/", (req, res, next) => {
const project = new Project({
_id: new mongoose.Types.ObjectId(),
projectName: req.body.projectName,
events: req.body.events
});
project
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "Created project successfully",
createdProject: {
projectName: result.projectName,
_id: result._id,
events: result.events,
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
module.exports = router;
my problem is I can't auto populate the enriched eventsId in projects page.
for eg. Whenever i update events they should appear in projects page.but its not happening. In events page also i am not getting corresponding projectId. please point me in right direction.
Populate method takes FIELD_TO_POPULATE and FIELDS_TO_RETURN_FROM_POPULATED_DOC and you are passing it the reversed way. Also in your project schema you have used events for EnrichedEvent, so while populating use events not EnrichedEvent;
Try the following:
From:
.populate('source', 'EnrichedEvents')
TO:
.populate('events', 'EnrichedEvent')
Edit:
update your schema for EnrichedEvent:
events: [{
mongoose.Schema.Types.ObjectId,
ref: 'EnrichedEvent'
}]
It should work now.
I tried to use a similar .populate('...', '...') method but unsuccessfully. I would use
.populate('source').populate('EnrichedEvent')
or ('EnrichedEvents') depending on what you have defined in your schema.
I have 2 collections, one is Credit, another one is User
credit
users
As you can see the credit's userId is the same with users's _id. How can I retrieve credit document when I retrieve that user? I've tried ref in schema but I don't get the data of credit, like so
exports.getUser = async function(req, res) {
const user = await User.findOne({_id: req.query.id})
.populate('credit')
.exec()
res.json(user)
}
CreditSchema
const CreditSchema = new Schema({
userId: Schema.Types.ObjectId,
credit: {
type: Number,
default: 0
},
log: [String]
})
UserSchema
const UserSchema = new Schema({
fullName: {
type: String
},
// etc.....
credit: {
type: Schema.Types.ObjectId,
ref: 'Credit'
}
})
Hello im new to nodejs and mongoose, i need help in mongoose populate, please help me to understand. Thanks in Advance!
here is my schema's
PropertySchema.js
const mongoose = require('mongoose')
const { Schema } = mongoose
require('./MemberSchema')
const propertySchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
pname: String,
ptype: String,
price: Number,
owner: { type: mongoose.Schema.Types.ObjectId, ref: 'Members' }
})
const Props = mongoose.model('Property', propertySchema)
module.exports = Property
MemberSchema.js
const mongoose = require('mongoose')
const { Schema } = mongoose
require('./PropertySchema')
const memberSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
fname: String,
lname: String,
dob: Number,
email: String,
address: String,
phone: Number,
memtype: String,
username: {type: String, required: true},
password: {type: String, required:true},
properties: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Property' }]
})
const Members = mongoose.model('Members', memberSchema)
module.exports = Members
addPropertyRoutes.js
router.post('/add', isAuthenticated, (req, res, next) => {
const props = new Property({
_id: new mongoose.Types.ObjectId(),
pname: req.body.pname,
ptype: req.body.ptype,
price: req.body.price,
owner: new mongoose.Types.ObjectId()
})
props.save( (err, props) => {
if (err) {
console.log('Unable to register your data: ' + err)
throw err
}
console.log('Property Added Successful!')
res.redirect('/property/add')
})
})
Im using mongoose 3.6 and expressjs.
When i check my Robo 3t after adding properties it shows like this check this screenshot:
In your, property schema you have to store ownerId, not to generate new ObjectId.
The proper way to do Populate in mongoose, you can find it here.
i think the solution is this:
change your addPropertyRoutes into this :)
router.post('/add', isAuthenticated, (req, res, next) => {
const member = req.user
Members.findOne({})
const props = new Property({
pname: req.body.pname,
ptype: req.body.ptype,
price: req.body.price,
owner: member._id
})
props.save( (err, props) => {
if (err) {
console.log('Unable to register your data: ' + err)
throw err
}
console.log('Registration Successful!')
res.redirect('/property/add')
})
})
Your Welcome from noobs