Comments (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)
- Virtuals not serialized after v8.5 HOT 3
- Cursor.next can return null, but TypeScript says it can't
- `this` context in nested schema `required` functions changed since mongoose 7.0.2+ HOT 2
- mongoose.connection.db can be undefined, but TypeScript says it can't
- Connection Error and not getting any data - DEP0170 HOT 1
- Intersection type error in embedded schema when iterating through an embedded array HOT 3
- Populate + lean + multiple populated documents leads to "Cannot read properties of undefined (reading '_id')" in version 8.5.2 HOT 1
- After replica election, mongoose can't connect to mongo db and throw timeout error each 30s HOT 2
- Issue deleted
- Model.bulkWrite options strict weird behavior HOT 1
- Question about .findOne() HOT 1
- can not specify zstd compression level HOT 4
- Mongoose.prototype.connect() : Discrepancy between changelog and example in document. HOT 1
- How to type added static methods and query helpers
- Transaction aborts when used with `ordered: false`
- Model.applyVirtuals(): apply schema virtuals to a POJO, similar to Model.applyDefaults() HOT 4
- Discriminator Method Modifies Schema Argument in Mongoose HOT 2
- Mongoose creates duplicate collections when name includes uppercase characters HOT 1
- There is a bug thats i dont save HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mongoose.