Populate doesn't return specified collection data - javascript

I have this credit schema
const CreditSchema = new Schema({
userId: Schema.Types.ObjectId,
credit: {
type: Number,
default: 0
},
log: [String]
})
I hope it can be retrieve in below call
exports.getUser = async function(req, res) {
const user = await User.findOne({_id: req.query.id})
.populate('credit')
.exec()
res.json(user)
}
But what I get is userSchema's data, I don't see the data from credit schema. This is how my userSchema look like
const UserSchema = new Schema({
name: {
type: String
},
credit: {
type: Schema.Types.ObjectId,
ref: 'Credit'
}
})
I really scratch my head, I have the data in my db and the _id of userSchema is the same with userId of creditSchema.
This is the data of User and Credit

Maybe like this:
User.findOne({_id: req.query.id})
.populate("credit")
.exec(function (err: any, result: any) {
...//code
})
});

Related

How to insert data into MongoDB collection?

I'm using NodeJS with Mongoose. I've two tables into db.js:
const mongoose = require('mongoose')
const UserSchema = new mongoose.Schema(
{
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true }
},
{ collection: 'users' }
)
const model = mongoose.model('UserSchema', UserSchema)
const AccountSchema = new mongoose.Schema(
{
username: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'hahaha' },
balance: { type: Number, required: true }
},
{ collection: 'accounts' }
)
module.exports.UserSchema = model
module.exports.AccountSchema = model
As you can see the first collection contains users (username, email, password). The second collection represents a bank account, related to a specific user. So, it has two fields: user (foreign key) and balance ($100, i.e.). First question: is my code correct to accomplish this task?
Second question: how can I insert data into the AccountSchema?
I obviously want to insert data only if the user exists into Userschema. I think that this doesn't work:
const Schema = require('./model/db')
app.post('/api/addaccount', async (req, res) => {
const { username, balance } = req.body
try {
const response = await Schema.AccountSchema.create({
username,
balance
})
console.log('User account successfully: ', response)
res.json({status : "ok"})
} catch (error) {
throw error
}
})
How can I do this?
This won't work. You've to query the User model first to check if any user exists with this username. If yes, you'll continue to store data in the Account model, if not you'll return a response something like user doesn't exist

Mongoose - creating and saving a document, then saving new document with its id

I have a user schema that looks like this:
const userSchema = new Schema({
email: {
type: String,
required: true,
unique: true,
trim: true
},
password: {
type: String,
required: true
},
role: {
type: String,
default: 'customer',
enum: ['customer', 'farmer', 'admin']
},
user_id: {
type: Schema.Types.ObjectId,
required: true,
unique: true
}
})
Additionally, I have another schema that would be called "customer" and looks something like this:
const customerSchema = new Schema({
company: String,
contact: String,
...etc
})
Now what I'd like to do is on creation of the User document, create and save a new Customer document, then save itd _id to my User document's user_id field.
The post request would look something like this:
// POST - USER REGISTRATION
router.post('/register', function (req, res) {
const { email, password, role } = req.body
const user = new User({ email, password, role,
user_id: new Customer({
company: req.body.company,
contact: req.body.contact,
...etc (rest of data)
})})
user.save(function(err) {
if (err) {
res.status(500)
.send("Failed to register. Please try again.")
}
else {
res.status(200).send("Registered.")
}
})
})
While this seems to create a Customer object (there's an ObjectID under user_id), the customer isn't saved to the database (naturally since .save isn't called).
My original approach here was to have a user_id variable set to null, then have customer create & save itself, then set the user_id variable to the customer._id value, but this didn't work as user.save(func(err)) would have a "null" user_id value.
just try like this
router.post("/register", async function (req, res) {
try {
const { email, password, role } = req.body;
let customer = new Customer({
company: req.body.company,
contact: req.body.contact,
});
let resultCustomer = await customer.save();
const user = new User({
email,
password,
role,
user_id: resultCustomer._id,
});
await user.save();
res.status(200).send("Registered.");
} catch (error) {
res.status(500).send("Failed to register. Please try again.");
}
});

Building A Referral System Using Nodejs

So am still kinda new to nodejs and am currently on a project and would to integrate a referral sytem into it. Basically on registering a user has a generated unique url that ither users can register with, i have gotten pass this part but now am trying to link the new user and the user who owns the link.
Here are my Models:
Referral Model
import mongoose, { mongo } from 'mongoose';
const referralSchema = new mongoose.Schema({
referralId: [
{
type: String,
unique: true
}
],
referralLink: {
type: String,
unique: true
},
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
},
createdAt: {
type: Date,
default: Date.now()
}
})
const Referral = mongoose.model("Referral", referralSchema);
export default Referral;
User Model
import mongoose from 'mongoose';
import passportLocalMongoose from 'passport-local-mongoose'
const userSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: {
type: String,
trim: true,
required: true,
unique: true,
lowercase: true
},
emailToken: String,
isVerified: Boolean,
username: String,
password: String,
isAdmin: Boolean,
refId: {
type: mongoose.Schema.Types.ObjectId,
ref: "referral",
},
walletId: {
type: mongoose.Schema.Types.ObjectId,
ref: "wallet",
},
plan: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "plan",
}
]
})
userSchema.plugin(passportLocalMongoose);
const User = mongoose.model("User", userSchema);
export default User;
And Here is my code
router.get('/verify-email', async (req, res, next) => {
try {
const user = await User.findOne({ emailToken: req.query.token });
if (!user) {
req.flash('error', 'Token is invalid, Please contact us for assistance');
return res.redirect('/');
}
user.emailToken = null;
user.isVerified = true;
const savedUser = await user.save().then((user) => {
//Create new referral for new user
const newReferrer = new Referral({
referralId: uuidv4(),
referralLink: uuidv4(),
userId: user._id,
});
//save referral to the database
newReferrer.save()
const customUserResponse = { user: savedUser }
customUserResponse.refCode = newReferrer.referralId
req.login(user, async (err) => {
if (err)
return next(err);
req.flash('success', `Welcome to Jenerouszy Mechanism ${user.username}`);
const redirectUrl = req.session.redirectTo || `/dashboard`;
delete req.session.redirectTo;
res.redirect(redirectUrl);
});
});
} catch (error) {
console.log(error);
req.flash('error', 'Something went wrong, please try again or contact us for assistance')
res.redirect('/')
}
});
router.get("/referrals", middlewareObj.isLoggedIn, (req, res) => {
Referral.findOne({ userId: req.user._id })
.populate('user') //Populate model with user
.then(loggedUser => {
//Generate random referral link
const generatedRefLink = `${req.protocol}://${req.headers.host}/register?reflink=${loggedUser.referralLink}/dashboard`
res.render('dashboard/referrals', {
loggedUser: loggedUser,
generatedRefLink: generatedRefLink
})
})
})
I don't know how to go about this, can someone please guide me on what to do.

Mongoose + Mongodb User.update not working

What I am trying to do is create a new collection, and push that collection into a specific User.collections array. I have read many stackoverflow posts and they all say to use either User.update() or User.findOneAndUpdate(). I am have no luck with either. I can create a Collection and that is saved to mongo so I know I am indeed accessing the db. Here is my code, if any of you can help I would appreciate it.
User Schema
const mongoose = require('mongoose');
const { Schema } = mongoose;
const userSchema = new Schema({
googleID: String,
givenName: String,
familyName: String,
collections: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "collection"
}
]
});
mongoose.model('users', userSchema);
Collection Schema:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const collectionSchema = new Schema({
type: String,
name: String,
gamesCollected: [
{
id: Number
}
]
});
mongoose.model('collection', collectionSchema);
And my route:
router.get('/get_collection', (req, res) => {
const collection = new Collection({
type: 'SNES',
name: 'First SNES Collection',
gamesCollected: [{ id: 5353 }]
}).save();
User.update({googleID: req.user.googleID}, {$push: {collections: collection}});
});
Save is not a synchronous operation but asynchronous so you need to use the promise it returns and handle it and once it is complete then update the user model. Something among these lines:
router.get('/get_collection', async (req, res) => {
let collection = new Collection({
type: 'SNES',
name: 'First SNES Collection',
gamesCollected: [{ id: 5353 }]
})
await collection.save().exec();
await User.update(
{googleID: req.user.googleID},
{$push: {collections: collection._id}}
).exec();
});

Save doesn't save any data

I'm trying to save some data into a local mongodb database.
My schema looks as follows:
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
email: String,
passwordHash: String,
registerTimeStamp: { type: Number, default: Date.now() },
usersFollowing: [],
accountStatus: {
isBanned: { type: Boolean, default: false },
reason: { type: String, default: '' }
}
});
module.exports = mongoose.model('User', userSchema);
and the insert Method looks like this:
createUser(name, email, password) {
const passwordHash = "asdf";
const user = new User({
_id: new mongoose.Types.ObjectId(),
name,
email,
passwordHash
});
user.save(console.log("saved"));
}
my problem is, that even though I called the method with the right arguments, and it prints "saved", no data is inserted into the database.
Thanks!
First of all, when you call:
user.save(console.log("saved"));
The console will print "saved" no matter if you get or not an error. So maybe you are getting an error without a proper handler. If you really want to know what is happening with your user instance:
user.save()
.then(() => console.log("saved"))
.catch((error) => console.log(error));
If you want to use callbacks instead of promises:
user.save(function(error) {
if(error) throw error;
console.log("saved");
});
Now, there is an error in your insert method.
Change:
_id: new mongoose.Types.ObjectId(),
With:
_id: new mongoose.Types.ObjectId,
The parenthesis is the problem.
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
email: String,
passwordHash: String,
registerTimeStamp: { type: Number, default: Date.now() },
usersFollowing: [],
accountStatus: {
isBanned: { type: Boolean, default: false },
reason: { type: String, default: '' }
}
});
const User = mongoose.model('User', userSchema);
module.exports = User;
module.exports.createUser = function (name, email, password) {
const passwordHash = "asdf";
const user = new User({
_id: new mongoose.Types.ObjectId(),
name,
email,
passwordHash
});
User.save(user , callback);
}
The problem is that you are just logging the message, not saving the user in your database.
In order to do that, first you have to export the user model doing something like this:
const UserModel = mongoose.model('User', userSchema)
module.exports = UserModel
Next, in the same file where you have the createUser method, you import the UserModel. Then in your createUser method, you call the .save method but from your model just imported, sending the just created user:
const UserModel = require('../pathtothefile') //Here you specify the path of the user-model file
createUser(name, email, password) {
const passwordHash = "asdf"
const user = new User({
_id: new mongoose.Types.ObjectId(),
name,
email,
passwordHash
})
return UserModel.save(user)
}

Categories

Resources