1
votes

the error occurs while I try to run the code but for my colleague, it does not throw an error up to this point

i tried to make syntax changes but did not workout.

var mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/blog_demo_2", {useNewUrlParser:true});

//POST schema

var postSchema = new mongoose.Schema({
    title: String,
    content: String,
});

var Post = mongoose.model("Post", postSchema);

//USER schema

var userSchema = new mongoose.Schema({
    name: String,
    email: String,
    posts: [
            {
                 type: mongoose.Schema.Types.ObjectID,   
                 ref: "Post"
            }
         ]
});

var User = mongoose.model("User", userSchema);

wasif4000:~/workspace/associations (master) $ node references.js
/home/ubuntu/workspace/node_modules/mongoose/lib/schema.js:414 throw new TypeError('Invalid value for schema path ' + prefix + key + ''); ^

TypeError: Invalid value for schema path `type`
    at Schema.add (/home/ubuntu/workspace/node_modules/mongoose/lib/schema.js:414:13)
    at new Schema (/home/ubuntu/workspace/node_modules/mongoose/lib/schema.js:117:10)
    at Schema.interpretAsType (/home/ubuntu/workspace/node_modules/mongoose/lib/schema.js:770:29)
    at Schema.path (/home/ubuntu/workspace/node_modules/mongoose/lib/schema.js:596:27)
    at Schema.add (/home/ubuntu/workspace/node_modules/mongoose/lib/schema.js:437:12)
    at new Schema (/home/ubuntu/workspace/node_modules/mongoose/lib/schema.js:117:10)
    at Object.<anonymous> (/home/ubuntu/workspace/associations/references.js:16:18)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:504:3
2

2 Answers

0
votes

the correction is

type: mongoose.Schema.Types.Object.Id,  

and not the below one where ID is uppercase, it should be lowercase

type: mongoose.Schema.Types.Object*ID*,
-1
votes

You have an extra comma in your code, look:

var postSchema = new mongoose.Schema({
    title: String,
    content: String,   ---->  You need to get rid of it
});

This should solve the problem.