Search code examples
node.jsmongodbmongoosemongoose-schema

How to check MongoDB to see if item already exist in collection


I've gotten my items into a collection in my database as an array of objects. Now I've noticed that the items are being added every time the server restarts, resulting in 6 instead of 3 products. How would I check the database to see if an item already exists within a collection so it's not duplicated? At the moment I'm getting 'ReferenceError: title is not defined'

Product.js (Model)

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ProductSchema = new Schema({
    product_id: {
        type: String,
        // required: true
    },
    imagepath: {
        type: String
        // required: true
    },
    title: {
        type: String
        // required: true
    },    
    description: {
        type: String
        // required: true
    },
    price: {
        type: Number
        // required: true
    },
});

Product-seeder.js(populates products collection)

module.exports = Product = mongoose.model('products', ProductSchema);
const Product = require('../models/Product');
const mongoose = require('mongoose');

const products = [
    new Product ({
        imagePath: '../client/src/Components/Layout/Media/armadillo.png',
        title: 'Pangolin',
        description: "This is a pangolin",
        price: 15000
    }),
    new Product ({
        imagePath: '../client/src/Components/Layout/Media/croc.png',
        title: 'Cuban corcodile',
        description: "This is a croc",
        price: 15000
    }),
    new Product ({
        imagePath: '../client/src/Components/Layout/Media/monkey.png',
        title: 'Golden Gibbon',
        description: "This is a monkey",
        price: 15000
    })
];

for (let i = 0; i < products.length; i++) {
    Product.findOne({title: title})
    .then(products => {
        if (!product) {
        products[i].save();
        } 
    }); 
}
mongoose.disconnect();

Solution

  • You did two mistakes in your query.

    Use products[i].title instead of title.

    Change Products with results or any other variable.

    for (let i = 0; i < products.length; i++) {
        console.log(products[i]);
        Product.findOne({title: products[i].title}) //products[i].title 
        .then(results => { //update products with results
          console.log(results)
            if (!results) {
            products[i].save();
            } 
        }); 
    }
    });