Find dont return array referece
See original GitHub issueHi!
Y have this:
Models:
import {
prop,
pre,
DocumentType,
ReturnModelType,
Ref,
} from '@typegoose/typegoose';
import validator from 'validator';
import bcrypt from 'bcrypt';
import { Role } from './Role';
@pre<User>('save', async function () {
const user = this;
if (!user.isModified('password')) return;
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(user.password!, salt);
user.password = hash;
})
export class User {
@prop({
type: String,
required: true,
lowercase: true,
trim: true,
validate: {
validator: function (v: string) {
return validator.isEmail(v);
},
message: "It's not a valid email",
},
})
public email?: string;
@prop({ type: String, required: true })
public username?: string;
@prop({ ref: () => Role })
public car?: Ref<Role>[];
@prop({ type: String, required: true })
public name?: string;
@prop({ type: String, required: true })
public surname?: string;
@prop({ type: String, required: true, minlength: 6 })
public password?: string;
@prop({ type: String })
public profilePic?: string;
//Instance method
public async comparePassword(
this: DocumentType<User>,
password: string
): Promise<boolean> {
return await bcrypt.compare(password, this.password!)!;
}
// Static method
public static async encryptPassword(
this: ReturnModelType<typeof User>,
password: string
) {
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(password!, salt);
return hash;
}
}
import { prop, ReturnModelType } from '@typegoose/typegoose';
import { ERoles } from 'shared/enums';
export class Role {
@prop({
type: String,
enum: ERoles,
unique: true,
required: true,
})
public name?: string;
static async insertRoles(this: ReturnModelType<typeof Role>) {
return this.insertMany([
{ name: ERoles.ADMIN },
{ name: ERoles.MANAGER },
{ name: ERoles.SENIOR },
{ name: ERoles.USER },
]);
}
static async findAllRoles(this: ReturnModelType<typeof Role>) {
const roles = await this.find();
return roles;
}
}
I’m using Next and Typegoose:
My api restpoint is:
case 'POST':
try {
const statusUser = EStatusUser.VERIFIED;
const newUser = new UserModel({
email: email,
username: username,
name: name,
surname: surname,
password: password,
status: statusUser,
});
await newUser.save();
if (roles.length === 1) {
const objectRol = await RoleModel.findOne({
name: req.body.roles.toString(),
});
const roleObjectString = objectRol?.id.toString();
await UserModel.findOneAndUpdate(
{ email: email },
{ $push: { car: roleObjectString } }
);
} else {
roles.forEach(async (rol: string) => {
const roleObject = await getRoleID(rol);
const roleObjectString = roleObject?.id.toString();
await UserModel.findOneAndUpdate(
{ email: email },
{ $push: { car: roleObjectString } },
{ new: true }
);
});
}
And my GET request is:
case 'GET':
try {
const users = await UserModel.find();
console.log('users :>> ', users);
return res.status(200).json({
success: true,
message: 'All Users',
data: users,
});
} catch (error) {
return res.status(200).json({
success: false,
message: 'Error in get Users',
});
}
And my response dont return the array reference de Car (what is the roles reference)
Version typegoose: 9.10.1
Issue Analytics
- State:
- Created a year ago
- Comments:6 (3 by maintainers)
Top Results From Across the Web
javascript return reference to array item - Stack Overflow
I tried to use Array.filter() function, but it returns a new array instead of a reference to the original array. which I can...
Read more >Chapter 7: Arrays - cs.utsa.edu
Objectives. Declare, Initialize, and Use Arrays; Use Loops for Array Traversal; Pass Arrays as Parameters; Return Arrays from Methods; Understand Reference ...
Read more >Dynamic array formulas and spilled array behavior
Excel formulas that return a set of values, also known as an array, return these values to neighboring cells. This behavior is called...
Read more >Returning values - Manual - PHP
Example #2 Returning an array to get multiple values. <?php ... To return a reference from a function, use the reference operator &...
Read more >ES6 Way to Clone an Array | SamanthaMing.com
To create a real copy of an array, you need to copy over the value of the array under a new value variable....
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
What is the data in the database? Are the refs (the objectIds) stored under
car
? If yes, then they should be returned, at least the array of objectIds. What is being returned in the response?Also, to get the values of the refs, you need to use
.populate
. https://mongoosejs.com/docs/populate.html#populateLastly, before you consider things being bugs, you should question your code and ask questions in either the Discussion forum here or in the Discord server for Typegoose to see if maybe the issue is with your code/ the usage of Typegoose. Because, Typegoose tests for this and it (obviously) works. https://github.com/typegoose/typegoose/blob/master/test/tests/ref.test.ts#L216
Scott
Closing Issue because it is marked as stale