Skip to content

Instantly share code, notes, and snippets.

@lineus lineus/andreygazhala.js Secret
Created Aug 27, 2018

What would you like to do?
try it with .exec()
#!/usr/bin/env node
'use strict';
const assert = require('assert');
const mongoose = require('mongoose');
const conn = mongoose.connection;
const Schema = mongoose.Schema;
const categorySchema = new Schema({
name: String
const Category = mongoose.model('category', categorySchema);
const category1 = new Category({ name: 'one' });
const category2 = new Category({ name: 'two' });
const articleSchema = new Schema({
text: String,
category: {
type: Schema.Types.ObjectId,
ref: 'category'
const Article = mongoose.model('article', articleSchema);
const article1 = new Article({ text: '1', category: category1._id });
const article2 = new Article({ text: '2', category: category1._id });
const article3 = new Article({ text: '3', category: category1._id });
async function deleteCategory(id) {
return Category.findByIdAndDelete(id, function(err, category) {
if (err) { return console.error(err); }
return Article.where({ category: }).updateMany({ category: category2._id }).exec();
async function run() {
await conn.dropDatabase();
await Category.create([category1, category2]);
await Article.create([article1, article2, article3]);
await deleteCategory(category1._id);
let docs = await Article.find();
let msg = 'id was not updated';
docs.forEach((doc) => assert.strictEqual(doc.category.toString(),, msg));
console.log('all articles updated correctly.');
return conn.close();
$: ./andreygazhala.js
all articles updated correctly.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.