I'm getting an error when adding it to the list of options:
Code:
.findOneAndUpdate(
{
ClientNo: req.query.ClientNo,
'Policies.PolicyID': req.query.PolicyID
},
{
$set: { 'Policies.$.Rules.$[rule].Benefits': req.body.Benefits }
},
{
arrayFilters: {}
},
(err, client) => {
if (err) next(this.handleError(err));
res.json(client);
}
)
Error:
Argument of type '{ arrayFilters: {}; }' is not assignable to parameter of type 'ModelFindOneAndUpdateOptions'.
Object literal may only specify known properties, and 'arrayFilters' does not exist in type 'ModelFindOneAndUpdateOptions'.
Here are my versions:
Apparently this does work. The value of arrayFilters needs to be an array though. Here's a working example on mongoose 5.0.14 and mongodb server 3.6.
#!/usr/bin/env node
'use strict';
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const conn = mongoose.connection;
const Schema = mongoose.Schema;
const sub = new Schema({
name: String
});
const schema = new Schema({
name: String,
nicks: [sub]
});
const Test = mongoose.model('test', schema);
const test = new Test({
name: 'Billy',
nicks: [{ name: 'hank' }, { name: 'willy'}]
});
async function run() {
await conn.dropDatabase();
await test.save();
const query = { name: 'Billy' };
const update = { $set: { 'nicks.$[elem].name': 'The Kid' } };
const options = { new: true, arrayFilters: [{ 'elem.name': 'hank' }]};
await Test.findOneAndUpdate(query, update, options);
let updated = await Test.findOne({});
console.log(updated);
return conn.close();
}
run();
mongoose5: ./6386.js
{ nicks:
[ { _id: 5ade5220d331ef9561a70985, name: 'The Kid' },
{ _id: 5ade5220d331ef9561a70984, name: 'willy' } ],
_id: 5ade5220d331ef9561a70983,
name: 'Billy',
__v: 0 }
mongoose5:
I'll update our api docs in a PR still though.
@zachrickards, Also, just curious, are you using typescript? This error:
Argument of type '{ arrayFilters: {}; }' is not assignable to parameter of type 'ModelFindOneAndUpdateOptions'.
Object literal may only specify known properties, and 'arrayFilters' does not exist in type 'ModelFindOneAndUpdateOptions'.
doesn't look like it came from mongoose or any of it's dependencies.
@lineus yup, using TS. I'll give it a try again and see if it works.
Array filters are new in MongoDB 3.6, so they won't work if you're using mongodb server 3.0.4.
Most helpful comment
Apparently this does work. The value of arrayFilters needs to be an array though. Here's a working example on mongoose 5.0.14 and mongodb server 3.6.
6386.js
Output:
I'll update our api docs in a PR still though.