mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

Query with or without `.lean()` changes datatype of result field

Open alex2600 opened this issue 6 years ago • 2 comments

Do you want to request a feature or report a bug? bug

What is the current behavior? The query result changes the datatype of a field depending on if .lean() is used in a query or not.

If the current behavior is a bug, please provide the steps to reproduce. To reproduce this behavior three steps (re-runs of the script) are required. All three steps are included in the script. You simply have to comment/uncomment the marked lines (with text "STEP N") in each step. So e.g. after the first run of this script (unchanged) you have to comment out all lines containing only "STEP 1" and uncomment all lines containing "STEP 2" and so on.

const mongoose = require("mongoose")

/////// Model ////////////////////////////////////////////////////////////////

const Markt = mongoose.model("Markt", {
   _id: Number,
   name: String,
})

const User = mongoose.model("User", {
   name: String,
   markt: {type: Number, ref: "markt", required: false}, // STEP 1
   // markt: [{type: Number, ref: "markt", required: false}], // STEP 2 & 3 (changing datatype of `markt` here)
})

/////// START ////////////////////////////////////////////////////////////////

connect()
   .then(clearData)  // STEP 1
   .then(addData)    // STEP 1
   .then(getUsers)
   .then(console.log)
   .catch(console.error)

/////// FNs ////////////////////////////////////////////////////////////////

async function connect () {
   await mongoose.connect('mongodb://localhost/highland-test-db', {
      useNewUrlParser: true,
      useUnifiedTopology: true
   })
}

async function addData () {
   await new Markt({_id: 1, name: "m1"}).save()
   await new Markt({_id: 2, name: "m2"}).save()
   await new User({name: "u1", markt: 1}).save()
   await new User({name: "u2", markt: 2}).save()
}

async function getUsers () {
   return User.find()      // STEP 1 & 2
   // return User.find().lean()  // STEP 3
}

async function clearData () {
   await User.remove()
   await Markt.remove()
}

What is the expected behavior? After changing the type of User.markt in step 2 the query delivers at first the expected result, a Array of Numbers: { markt: [ 1 ], _id: 5eb2c39a5dcd7136dcf7137a, name: 'u1', __v: 0 }

When using .lean() in a query (STEP 3) the datatype of User.markt changes to Number again in the result: { _id: 5eb2c39a5dcd7136dcf7137a, name: 'u1', markt: 1, __v: 0 }

I am expecting the datatype of User.markt not to change with or without .lean(). I am expecting the datatype of User.markt to be a Array of Numbers.

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version. Node v12.16.2 Mongoose v5.9.12 MongoDb v3.6.11

alex2600 avatar May 06 '20 14:05 alex2600

This is by design, mongoose casts the values returned from the database to match the schema. If you want to bypass casting, you'll need to use .lean().

If you want to cast, but still get a raw object, you'll need to omit .lean(), you can use user.toObject().

const mongoose = require('mongoose');
const assert = require('assert');

run().catch(console.error);


async function run () {
  await mongoose.connect('mongodb://localhost/highland-test-db', {
    useNewUrlParser: true,
    useUnifiedTopology: true
  });

  await mongoose.connection.dropDatabase();

  const Market = mongoose.model('Market', { _id: Number, name: String });

  const User = mongoose.model('User', {
    name: String,
    market: [{ type: Number, ref: 'Market', required: false }]
  });

  await Promise.all([
    Market.create([
      { _id: 1, name: 'm1' },
      { _id: 2, name: 'm2' }
    ]),
    // bypassing schema
    User.collection.insertMany([
      { name: 'u1', market: 1 },
      { name: 'u2', market: 2 }
    ])
  ]);


  const user = await User.findOne({ name: 'u1' });
  const rawCastUser = user.toObject();

  assert.deepEqual(rawCastUser.market, [1]);

  console.log('All assertions passed.');
}

AbdelrahmanHafez avatar May 06 '20 16:05 AbdelrahmanHafez

Ok that seems weird but thanks for the info. Then I will need to handle this problem in my code.

alex2600 avatar May 06 '20 19:05 alex2600