Git Product home page Git Product logo

Comments (1)

vkarpov15 avatar vkarpov15 commented on August 22, 2024 1

Yes, there's the clone option that was introduced with #3258. For example, the following script demonstrates the issue you're facing, 2 documents end up with sender.avatar set to 'avatar1.png?signed=true?signed=true'

const mongoose = require('mongoose');

// MongoDB connection URL
const MONGO_URI = 'mongodb://localhost:27017/mongoose_repro';

// Placeholder function to simulate URL signing
async function signUrl(avatarUrl) {
  // Simulate signing process
  return `${avatarUrl}?signed=true`;
}

const userSchema = new mongoose.Schema({
  username: String,
  avatar: String,
});

const messageSchema = new mongoose.Schema({
  chat: mongoose.Schema.Types.ObjectId,
  sender: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  text: String,
  createdAt: { type: Date, default: Date.now },
});

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

async function main() {
  await mongoose.connect(MONGO_URI);
  console.log('Connected to MongoDB');

  await User.deleteMany({});
  await Message.deleteMany({});

  // Create sample users and messages
  const user1 = new User({ username: 'user1', avatar: 'avatar1.png' });
  const user2 = new User({ username: 'user2', avatar: 'avatar2.png' });
  await user1.save();
  await user2.save();

  const chatId = new mongoose.Types.ObjectId();
  const messages = [
    new Message({ chat: chatId, sender: user1._id, text: 'Hello from user1' }),
    new Message({ chat: chatId, sender: user1._id, text: 'Another message from user1' }),
    new Message({ chat: chatId, sender: user2._id, text: 'Hello from user2' }),
  ];
  await Message.insertMany(messages);

  // Query and populate
  const populatedMessages = await Message.find({ chat: chatId })
    .sort({ createdAt: 1 })
    .populate('sender')
    .exec();

  // Attempt to sign avatars
  for (let message of populatedMessages) {
    message.sender.avatar = await signUrl(message.sender.avatar);
  }

  console.log('Populated Messages:', populatedMessages);

  // Clean up
  await mongoose.connection.close();
}

main().catch(err => console.error(err));

To fix, add the clone option to populate():

  // Query and populate
  const populatedMessages = await Message.find({ chat: chatId })
    .sort({ createdAt: 1 })
    .populate({ path: 'sender', clone: true }) // <-- add `clone: true` to make Mongoose clone result documents and avoid multiple messages having the same `sender`
    .exec();

from mongoose.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.