-
-
Notifications
You must be signed in to change notification settings - Fork 4k
Open
Description
Prerequisites
- I have written a descriptive issue title
- I have searched existing issues to ensure the issue has not already been raised
Issue
Setters should run with setDefaultsOnInsert
'use strict';
const mongoose = require('mongoose');
const { Schema } = mongoose;
const assert = require('assert');
const { MongoMemoryServer } = require('mongodb-memory-server');
run().catch(err => {
console.error(err);
process.exit(1);
});
async function run() {
const mongod = await MongoMemoryServer.create();
try {
await mongoose.connect(mongod.getUri(), { dbName: 'test' });
const schema = new Schema({
name: String,
slug: {
type: String,
default: 'Hello World!',
set: function(v) {
return v.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
}
}
});
const Test = mongoose.model('Test', schema);
// Normal document creation: setter runs on default
const doc = new Test({ name: 'test' });
assert.equal(doc.slug, 'hello-world');
// Upsert: setter does NOT run on default
await Test.updateOne(
{ name: 'test2' },
{ $set: { name: 'test2' } },
{ upsert: true, setDefaultsOnInsert: true }
);
const upserted = await Test.findOne({ name: 'test2' });
assert.equal(upserted.slug, 'hello-world');
console.log('PASS');
} finally {
await mongoose.disconnect();
await mongod.stop();
}
}Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels