Created
February 26, 2018 02:04
-
-
Save AlfieriChou/bba78cb59ba61b76d6cbe184181a4dba to your computer and use it in GitHub Desktop.
mongoose arrayFilters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mongoose from 'mongoose'; | |
run().catch(error => console.error(error.stack)); | |
async function run() { | |
await mongoose.connect('mongodb://localhost:27017/test'); | |
await mongoose.connection.dropDatabase(); | |
const BlogPost = mongoose.model('BlogPost', new mongoose.Schema({ | |
title: String, | |
comments: [{ _id: false, author: String, text: String }] | |
}), 'BlogPost'); | |
// Insert 2 docs | |
await BlogPost.create({ | |
title: 'A Node.js Perspective on MongoDB 3.6: Array Filters', | |
comments: [ | |
{ author: 'Foo', text: 'This is awesome!' }, | |
{ author: 'Bar', text: 'Where are the upgrade docs?' } | |
] | |
}); | |
await BlogPost.create({ | |
title: 'What\'s New in Mongoose 5: Improved Connections', | |
comments: [ | |
{ author: 'Bar', text: 'Thanks!' }, | |
{ author: 'Bar', text: 'Sorry for double post' } | |
] | |
}); | |
// Update docs using `arrayFilters` and `$[]` | |
await BlogPost.updateMany({ 'comments.author': 'Bar' }, | |
{ $set: { 'comments.$[element].author': 'Baz' } }, | |
// `$[element]` is tied to name `element` below | |
{ arrayFilters: [{ 'element.author': 'Bar' }] }); | |
const docs = await BlogPost.find(); | |
// [ [ { author: 'Foo', text: 'This is awesome!' }, | |
// { author: 'Baz', text: 'Where are the upgrade docs?' } ], | |
// [ { author: 'Baz', text: 'Thanks!' }, | |
// { author: 'Baz', text: 'Sorry for double post' } ] ] | |
console.log(docs.map(doc => doc.comments)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment