Schema Hasn T Been Registered For Model Products

Find the data you need here

We provide programming data of 20 most popular languages, hope to help you!

Previous PostNext Post

MissingSchemaError: Schema hasn't been registered for model products

const mongoose = require('mongoose');
const cartSchema = new mongoose.Schema({
    user: { type: mongoose.Schema.Types.ObjectId, ref: 'user', required: true },
    cartItems: [
        {
        product : {
            type :mongoose.Schema.Types.ObjectId, 
            ref : "product",
            required:true
        },
        quantity : {
            type:Number,
            default:1
        }
    }
    ]
} ,{timestamps:true});

module.exports = mongoose.model('Cart' , cartSchema , 'cart');
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        trim: true
    },
    slug: {
        type: String,
        required: true,
        unique: true
    },
    quantity: {
        type: Number,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    description: {
        type: String,
        required: true,
        trim: true
    },
    offer: { type: Number },
    productPictures: [{
        img: { type: String }
    }],
    reviews: [{
        userid: { type: mongoose.Schema.Types.ObjectId, ref: "User", review: String }
    }],
    category: { type: mongoose.Schema.Types.ObjectId, ref: "Categories" },
    createdby: {
        type: mongoose.Schema.Types.ObjectId, ref: "User", required: true
    },
    updatedAT: {
        type: Date
    }

}, { timestamps: true });

module.exports = mongoose.model('Product', productSchema);
{"_id":{"$oid":"6027d3a8cf712436607e6a6f"},"name":"Samsung Galaxy S21 Plus (Phantom Silver, 256 GB)  (8 GB RAM)","slug":"Samsung-Galaxy-S21-Plus-(Phantom-Silver-256-GB)-(8-GB-RAM)","price":5000,"quantity":10,"description":"With the Samsung Galaxy S21 Plus Smartphone, you can click amazing shots and record stunning videos at up to 8K resolution as it comes with a 64 MP camera setup. This smartphone is 5G-ready, enabling you to stream videos and download content from the Web with minimal lag. Moreover, its powerful processor and long-lasting battery make it a delight to use this smartphone.","productPictures":[{"_id":{"$oid":"6027d3a8cf712436607e6a70"},"img":"wGFfBkAhQ-samsung-galaxy-j6-sm-j600gzbgins-original-imaf6zpf6q8tjcva.jpeg"}],"category":{"$oid":"6020d53117616c5228246ac4"},"createdby":{"$oid":"601400873e5a422f9c81ae1c"},"reviews":[],"createdAt":{"$date":"2021-02-13T13:27:04.135Z"},"updatedAt":{"$date":"2021-02-13T13:27:04.135Z"},"__v":0}
{"_id":{"$oid":"6027d3bacf712436607e6a71"},"user":{"$oid":"60238bea8f89fb538c845f5b"},"cartItems":[{"quantity":2,"_id":{"$oid":"6027d3d4cf712436607e6a73"},"product":{"$oid":"6027d3a8cf712436607e6a6f"}}],"createdAt":{"$date":"2021-02-13T13:27:22.393Z"},"updatedAt":{"$date":"2021-02-13T13:27:48.217Z"},"__v":0}
exports.getCartItems = (req, res) => {
  //const { user } = req.body.payload;
  //if(user){
    console.log('req.user._id' , req.user._id);
    Cart.findOne({ user: req.user._id })
    .populate("cartItems.product", "_id name price productPictures")
    .exec((error, cart) => {
    console.log('getCartItems' , error);
      if (error) return res.status(400).json({ error });
      if (cart) {
        let cartItems = {};
        cart.cartItems.forEach((item, index) => {
          cartItems[item.product._id.toString()] = {
            _id: item.product._id.toString(),
            name: item.product.name,
            img: item.product.productPictures[0].img,
            price: item.product.price,
            qty: item.quantity,
          };
        });
        res.status(200).json({ cartItems });
      }
    });
  //}
};
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var userSchema = new Schema({
    (define schema)
});
...
(save user)
...
(check password)
...
mongoose.model('User', userSchema);
var mongoose = require('mongoose');
var User = mongoose.model('User');
MissingSchemaError: Schema hasn't been registered for model "User".
module.exports = mongoose.model('User', userSchema);
mongoose.connect("mongodb://localhost/news");
require("./models/Posts");
require("./models/Comments");

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();
var mongoose = require('mongoose');
//Load all your models
var User = require('./../models/user.js');

//Now, this call won't fail because User has been added as a schema.
mongoose.model('User');
var models_path = __dirname + '/app/models'
fs.readdirSync(models_path).forEach(function (file) {
  if (~file.indexOf('.js')) require(models_path + '/' + file)
})
product: {
    type: mongoose.Schema.ObjectId,
    ref: 'Product', <-- Should be same as modelName
    required: [true, 'Cart must belong to a product']
}
'use strict';
require('../models/settingsModel'); // load settingsModel.js file before get mongoose.model('Settings')
var mongoose = require('mongoose'),
    Settings = mongoose.model('Settings'),
    Q = require('q');
const userSchema = new Schema({
// ...
});
module.exports = mongoose.model('User', userSchema);
const productSchema = new Schema({
// ...
  userId: {
    type: Schema.Types.ObjectId,
    ref: 'user', // This should exactly match the name of User model above!!!
    required: true
  }
});
    import { model, Schema } from 'mongoose';
    import Company from './CompanyModel';

    const ProjectSchema = new Schema({
        company: { type: Schema.Types.ObjectId, ref: "Company" }
    });

    export default model('Project', ProjectSchema);
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Role = require("./role");
const userSchema = new Schema(
  {
    role: { type: Schema.Types.ObjectId, ref: "Role", required: false },
    username: { type: String, required: true, trim: true },
    password: { type: String, required: true, trim: true },
    email: { type: String, required: true, trim: true }
  },
  { timestamps: true }
);

module.exports = mongoose.model("User", userSchema);
var mongoose = require('./config/mongoose'), 
    express = require('./config/express');
require('./model1');
require('./model2');
require('./model3');
require('./app/models');
mongoose.model('Model1')
const playerSchema = new Schema({
    bowling: {
        style: String,
        arm: String,
    }
})

export const PlayerSchema = model('Player', playerSchema)
//blog.js file

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

const blogSchema = new Schema({
title : String
});

mongoose.model('blogs', blogSchema);
//server.js file
require('dotenv').config();
const mongoose = require('mongoose');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
require('./models/blog');
const Blog = mongoose.model('blogs');

const URL = process.env.MONGO_DB_URL;
 mongoose.connect(URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

mongoose.connection
.once('open', () => console.log('Connected to MongoLab instance.'))
.on('error', (error) => console.log('Error connecting to MongoLab:', error));

const app = express();

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/',  (req,res)=>{
res.send('Hello World')
});

 app.post('/blog',async (req, res) =>{
    const blog = await new Blog(req.body).save();
    res.send('just an example');
  });
// models/User.js
const userSchema = new Schema({ name: String });
module.exports = mongoose.model('User', userSchema); // note the 1st arg


// models/Post.js
const postSchema = new Schema({ 
   user: { 
     type: mongoose.Schema.Types.ObjectId, 
     ref: 'User' // `ref` must be 'User' not 'user'
   },
})

module.exports = mongoose.model('Post', postSchema)
// your app
const User = require('./models/User') // important to import
const Post = require('./models/Post')

//console.log(!!mongoose.models.User) // true
//..
const post = await Post.findOne().populate({ path : 'user' })
// models/User.js
const userSchema = new Schema({ name: String });
module.exports = mongoose.model('User', userSchema);


// models/Post.js
const User = require('./User')

const postSchema = new Schema({ 
   user: { 
     type: mongoose.Schema.Types.ObjectId, 
     ref: User, // here we are directly referring model instance itself instead of model name.
   }
});

module.exports = mongoose.model('Post', postSchema)
grunt test
mocha

Mgan59 / mongoose-fixture Public

var allFixtures = [    
    {
        schema:'Product',
        data:'product',
        collection:'products'
    }  
];
// history.js
module.exports = function(mongoose, conn) {
    var ProductSchema = mongoose.model('Product').schema;
    var HistorySchema = new mongoose.Schema({
        ...
        products: {
            type: [ProductSchema]
        }
    });

    mongoose.model('History', HistorySchema);
    return {
        name: 'History',
        schema: HistorySchema
    };
};
/*
 *  File: product.js
 *  Type: DataFixture
 *  Generated by: Mongoose-Fixture (v0.4.1)
 *
 */

module.exports = function(mongoose, conn, callback) {

    // standard callback error
    var error = null;

    // create your data documents using object-literals
    var fixture = [];

    /*
     * Example of adding a data document/fixture item
     */
    fixture.push({
        // by not defining an _id mongoose-fixture
        // will by default set a mongo ObjectID
        // defining one manually will override mongoDB
        name: "Play for Java: Covers Play 2",
        type: "Book",
        description: "Play for Java shows you how to build Java-based web applications using the Play 2 framework...",
        company: "Manning Publications",
        price: 30,
        imagePath: "/public/assets/images/play-for-java.png",
        rating: 4.5,
        category: "Computer",
        author: "Nicolas Leroux",
        publicationDate: "2014-03-31",
        numPage: 320
    });
    return callback(error, fixture);
};
module.exports = function(mongoose, conn) {
    var ProductSchema = mongoose.Schema({
        name: {
            type: String
        },
        type: {
            type: String
        },
        description: {
            type: String
        },
        company: {
            type: String
        },
        price: {
            type: Number
        },
        imagePath: {
            type: String
        },
        imageName: {
            type: String
        },
        rating: {
            type: Number
        },
        comments: {
            type: Array
        },
        userId: {
            type: String
        },
        category: {
            type: String
        },
        author: {
            type: String
        },
        publicationDate: {
            type: Date
        },
        numPage: {
            type: Number
        }
    });

    mongoose.model('Product', ProductSchema);

    return {
        name: 'Product',
        schema: ProductSchema
    };
};
// history.js
module.exports = function(mongoose, conn) {
    var Schema = mongoose.Schema;
    var HistorySchema = new mongoose.Schema({
        ...
        products: {
           type: Schema.Types.ObjectId, 
           ref: 'product', 
           required: true
        }
    });

    // I would recommend not registering your schemas here as it can create
    // a coupling issue when trying to share schemas/models with other services like express
    mongoose.model('History', HistorySchema);

    return {
        name: 'History',
        schema: HistorySchema
    };
};

Automattic / mongoose Public

/var/www/html/noodetest/node_modules/mongoose/lib/index.js:329
      throw new mongoose.Error.MissingSchemaError(name);
            ^
MissingSchemaError: Schema hasn't been registered for model "User".
Use mongoose.model(name, schema)
    at Mongoose.model (/var/www/html/noodetest/node_modules/mongoose/lib/index.js:329:13)
    at Object.<anonymous> (/var/www/html/noodetest/app/models/rrss.js:3:29)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/var/www/html/noodetest/server.js:36:14)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3
var mongoose     = require('mongoose'),
    Schema       = mongoose.Schema,
    Social       = mongoose.model('Social');

var userSchema   = new mongoose.Schema({
    name: { type:  Schema.Types.String, required: true },
    nick: { type:  Schema.Types.String, required: true },
    bio: { type:  Schema.Types.String, required: true },
    avatar: { type:  Schema.Types.String, required: false },
    rrss: [
        {
            type: Schema.Types.ObjectId, ref: 'Social'
        }
    ]
});

module.exports = mongoose.model('User', userSchema);
var mongoose     = require('mongoose'),
    Schema       = mongoose.Schema,
    User         = mongoose.model('User');

var socialSchema   = new mongoose.Schema({
    twitter: { type:  Schema.Types.String },
    github: { type:  Schema.Types.String },
    web: { type:  Schema.Types.String },
    user_id: [
        {
            type: Schema.Types.String, ref: 'User'
        }
    ]
});

module.exports = mongoose.model('Social', socialSchema);
// Load models
var Social = require('./app/models/rrss'),
    User   = require('./app/models/user'),
    Schema = mongoose.Schema;
require('./user-model.js');
require('./item-model.js');
UserSchema.statics.foo = async function () {
  ...
  const result = await Item.bar();
  ...
};

Strapi / strapi Public

error MissingSchemaError: Schema hasn't been registered for model "product".
Use mongoose.model(name, schema)
    at new MissingSchemaError (/Users/vladcazacu/projects/strapi-test-project/node_modules/mongoose/lib/error/missingSchema.js:22:11)
    at NativeConnection.Connection.model (/Users/vladcazacu/projects/strapi-test-project/node_modules/mongoose/lib/connection.js:1029:11)
    at getModelsMapForPopulate (/Users/vladcazacu/projects/strapi-test-project/node_modules/mongoose/lib/helpers/populate/getModelsMapForPopulate.js:201:59)
    at populate (/Users/vladcazacu/projects/strapi-test-project/node_modules/mongoose/lib/model.js:4250:21)
    at _populate (/Users/vladcazacu/projects/strapi-test-project/node_modules/mongoose/lib/model.js:4220:5)
    at /Users/vladcazacu/projects/strapi-test-project/node_modules/mongoose/lib/model.js:4195:5
    at Object.promiseOrCallback (/Users/vladcazacu/projects/strapi-test-project/node_modules/mongoose/lib/utils.js:261:12)
    at Function.Model.populate (/Users/vladcazacu/projects/strapi-test-project/node_modules/mongoose/lib/model.js:4193:16)
    at cb (/Users/vladcazacu/projects/strapi-test-project/node_modules/mongoose/lib/query.js:1948:17)
    at /Users/vladcazacu/projects/strapi-test-project/node_modules/mongodb/lib/operations/execute_operation.js:75:17
    at executeCallback (/Users/vladcazacu/projects/strapi-test-project/node_modules/mongodb/lib/operations/execute_operation.js:68:9)
    at handleCallback (/Users/vladcazacu/projects/strapi-test-project/node_modules/mongodb/lib/utils.js:129:55)
    at /Users/vladcazacu/projects/strapi-test-project/node_modules/mongodb/lib/operations/to_array.js:36:13
    at handleCallback (/Users/vladcazacu/projects/strapi-test-project/node_modules/mongodb/lib/utils.js:129:55)
    at completeClose (/Users/vladcazacu/projects/strapi-test-project/node_modules/mongodb/lib/cursor.js:859:16)
    at Cursor.close (/Users/vladcazacu/projects/strapi-test-project/node_modules/mongodb/lib/cursor.js:878:12)```
"product_attributes": {
  "via": "product",
  "collection": "product-attribute"
},
"product_variants": {
  "via": "product",
  "collection": "product-variant"
}

Automattic / mongoose Public

const PlatformSchema = new Mongoose.Schema({
  name: String
});
const PlatformModel = Mongoose.model('platform', PlatformSchema);
const PlaceSchema = new Mongoose.Schema({
  name: String,
  platform: {
    type: Mongoose.Schema.Types.ObjectId,
    ref: PlatformSchema
  }
});
const PlaceModel = Mongoose.model('place', PlaceSchema);
PlaceModel
      .findOne({ _id: '5b7f97894e43f174cb0f42cc' })
      .populate({ path: 'platform' })
{ MissingSchemaError: Schema hasn't been registered for model "[object Object]".
Use mongoose.model(name, schema)
    at new MissingSchemaError (/path/to/my/project/node_modules/mongoose/lib/error/missingSchema.js:20:11)
    at NativeConnection.Connection.model (/path/to/my/project/node_modules/mongoose/lib/connection.js:791:11)
    at getModelsMapForPopulate (/path/to/my/project/node_modules/mongoose/lib/model.js:4000:20)
    at populate (/path/to/my/project/node_modules/mongoose/lib/model.js:3502:21)
    at _populate (/path/to/my/project/node_modules/mongoose/lib/model.js:3472:5)
    at utils.promiseOrCallback.cb (/path/to/my/project/node_modules/mongoose/lib/model.js:3445:5)
    at Object.promiseOrCallback (/path/to/my/project/node_modules/mongoose/lib/utils.js:231:14)
    at Function.Model.populate (/path/to/my/project/node_modules/mongoose/lib/model.js:3444:16)
    at model.Query.Query._completeOne (/path/to/my/project/node_modules/mongoose/lib/query.js:1814:9)
    at Immediate.Query.base.findOne.call (/path/to/my/project/node_modules/mongoose/lib/query.js:1851:10)
    at Immediate._onImmediate (/path/to/my/project/node_modules/mquery/lib/utils.js:117:16)
    at runCallback (timers.js:810:20)
    at tryOnImmediate (timers.js:768:5)
    at processImmediate [as _immediateCallback] (timers.js:745:5)
  message: 'Schema hasn\'t been registered for model "[object Object]".\nUse mongoose.model(name, schema)',
  name: 'MissingSchemaError' }
3421. // Note that we didn't need to specify the Weapon model because
3422. // it is in the schema's ref
  platform: {
    type: Mongoose.Schema.Types.ObjectId,
    ref: 'platform'
  }
 const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const router = express.Router();

const indexRoute = require('./routes/index-route');
const productsRoute = require('./routes/products-route');


mongoose.connect('mongodb://login:[email protected]:58548/ndstr');


const Product = require('./models/product');
'use strict';

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

const schema = new Schema({
    title: {
        type: String,
        required: true,
        trim: true
    },
    slug:{
        type: String, 
        required: true,
        trim: true,
        index: true,
        unique: true
    },
    description: {
        type: String,
        required: true,
    },
    price: {
        type: Number,
        required: true
    },
    active: {
        type: Boolean,
        required: true,
        default: true
    },
    tags: [{
        type: String,
        required: true
    }]
});

module.exports = mongoose.model('Product', schema);
'use strict';

const mongoose = require('mongoose');
const Product = mongoose.model('Product');

exports.post = (req, res, next) => {
    var product = new Product(req.body);
    product.save().then(x => {
        res.status(201).send({ mesage: "Produto cadastrado com sucesso!'" });
    }).catch(e => {
        res.status(400).send({
            message: '[ERRO] Falha durante cadastro!',
            data: e
        });
    });
    res.status(201).send(req.body);
};
exports.put = (req, res, next) => {
    const id = req.params.id;
    res.status(200).send({
        id: id,
        item: req.body
    });
};
exports.delete = (req, res, next) => {
    res.status(201).send(req.body);
};
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));

const indexRoute = require('./routes/index-route');
const productsRoute = require('./routes/products-route');

mongoose.connect('mongodb://login:[email protected]:58548/ndstr',
    { 
        useNewUrlParser: true , 
        useCreateIndex: true
    });

//const Product = require('./models/product');

app.use('/produtos', productsRoute);
const mongoose = require('mongoose');
//const Schema = moongose.Schema;
//const schema = new mongoose.Schema({
const productSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
        trim: true
    },
    slug:{
        type: String, 
        required: true,
        trim: true,
        index: true,
        unique: true
    },
    description: {
        type: String,
        required: true,
    },
    price: {
        type: Number,
        required: true
    },
    active: {
        type: Boolean,
        required: true,
        default: true
    },
    tags: [{
        type: String,
        required: true
    }]
});

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

exports.post = (req, res, next) => {
    var product = new Product(req.body);
    product.save().then(x => {
        res.status(201).send({ mesage: "Produto cadastrado com sucesso!'" });
    }).catch(e => {
        res.status(400).send({
            message: '[ERRO] Falha durante cadastro!',
            data: e
        });
    });
    res.status(201).send(req.body);
};
exports.put = (req, res, next) => {
    const id = req.params.id;
    res.status(200).send({
        id: id,
        item: req.body
    });
};
exports.delete = (req, res, next) => {
    res.status(201).send(req.body);
};

Previous PostNext Post

Related code examples