Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Automatically translateAliases() for queries and updates #8678

Closed
akash-gupt opened this issue Mar 17, 2020 · 7 comments
Closed

Automatically translateAliases() for queries and updates #8678

akash-gupt opened this issue Mar 17, 2020 · 7 comments
Labels
new feature This change adds new functionality, like a new method or class
Milestone

Comments

@akash-gupt
Copy link

akash-gupt commented Mar 17, 2020

import {
  addModelToTypegoose,
  arrayProp,
  buildSchema,
  getModelForClass,
  index,
  mongoose,
  plugin,
  pre,
  prop,
  Ref,
} from '@typegoose/typegoose';



export class Product extends BaseModel<Product> {
  static readonly collectionName = 'Products';
  @prop({
    required: true,
    index: true,
    sparse: true,
    alias: 'name2',
  })
  name: string;

}


import { SchemaOptions } from 'mongoose';

export const schemaOptions: SchemaOptions = {
  strict: true,
  timestamps: true,
  selectPopulatedPaths: false,
  minimize: true,
  toJSON: {
    virtuals: true,
    getters: true,
    transform: (doc, ret, options) => {
      delete ret.deleted;
      delete ret.__v;
      delete ret._id;
    },
  },
  toObject: {
    virtuals: true,
    getters: true,
    transform: (doc, ret, options) => {
      delete ret.deleted;
      delete ret.__v;
      delete ret._id;
    },
  },
};

I am not able to run an update query

Debug log
Mongoose: Products.updateOne({ _id: ObjectId("5e6e2c2ea1e74d2362c593e3") }, { '$setOnInsert': { createdAt: new Date("Tue, 17 Mar 2020 15:13:57 GMT") }, '$set': { updatedAt: new Date("Tue, 17 Mar 2020 15:13:57 GMT") }}, {})

AbdelrahmanHafez added a commit to AbdelrahmanHafez/mongoose that referenced this issue Mar 18, 2020
@AbdelrahmanHafez
Copy link
Collaborator

AbdelrahmanHafez commented Mar 18, 2020

Mongoose currently doesn't support querying/updating with aliases.

Meanwhile, you can use Model.translateAliases(...)

'use strict';

const mongoose = require('./');
const { Schema } = mongoose;
const assert = require('assert');

mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true });

const userSchema = new Schema({
  name: { type: String, alias: 'nameAlias' }
});

const User = mongoose.model('User', userSchema);

async function run() {
  await User.deleteMany();

  const user = await User.create({ nameAlias: 'Hafez' });

  const filter = User.translateAliases({ nameAlias: 'Hafez' });
  const changes = User.translateAliases({ nameAlias: 'new name' });

  await User.updateOne(filter, changes);


  const updatedUser = await User.findOne({ _id: user._id });
  assert.equals(updatedUser.nameAlias, 'new name');
}


run().catch(console.error);

@vkarpov15 vkarpov15 changed the title alias not working with updateOne query Automatically translateAliases() for queries and updates Mar 20, 2020
@vkarpov15 vkarpov15 added this to the 5.9.6 milestone Mar 20, 2020
@vkarpov15 vkarpov15 modified the milestones: 5.9.6, 5.x Unprioritized Mar 21, 2020
@IslandRhythms IslandRhythms added the new feature This change adds new functionality, like a new method or class label Jan 28, 2021
@mazyvan
Copy link

mazyvan commented Apr 14, 2021

Waiting for this feature. It will be really useful.

@komarevtsevdn
Copy link

Yeah, waiting too

@frdel
Copy link

frdel commented Oct 22, 2021

Please, this is such an easy fix and would be so helpful...

@AbdelrahmanHafez
Copy link
Collaborator

The team's resources are currently focused on other issues, PRs implementing this functionality are welcome.

@vishnupeas
Copy link

why does the update work for lower-level aliases and not for the top-level fields?

eg:

const moduleSchema = mongoose.Schema(
    {
        mt: { type: Number, required: true, alias: "type" },
        mp: { type: [Number], required: true, alias: "permissions" },
    }
)

const roleSchema = mongoose.Schema(
    {
        n: { type: String, required: true, alias: "name" },
        m: { type: [moduleSchema], required: true, alias: "modules" },
    }
)

now when i call findByIdAndUpdate, the data passed gets updated if data is

data = {
    n: "admin",
    m: {
        type: 2,
        permission: [1, 2, 3],
    },
}

and fails to update when if pass data as

data = {
    name: "HR",
    modules: {
        type: 2,
        permission: [1, 2, 3],
    },
}

@vishnupeas
Copy link

I also noticed translateAliases only changes the field values shallow and not does consider the aliases that are deeper nested, the same case as the findByIdAndUpdate function.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
new feature This change adds new functionality, like a new method or class
Projects
None yet
Development

No branches or pull requests

8 participants