引用另一个模式时 mongoDB 中的验证错误?

Validation Error in mongoDB while making a reference to another Schema?

我在 mongo 中创建了一个博客架构,它引用了用户架构。 但是,当我尝试将博客保存在 MongoDB 中时,出现以下错误:-

CUrrrent post user:  new ObjectId("61d28db34c78f60375189033")
User validation failed: passwordHash: Path `passwordHash` is required., name: Path `name` is required., username: Path `username` is required.

我正在通过 JSON

发送
{
        "title": "Best Copywriting formulas!",
        "author": "Copywriters Inc.",
        "url": "https://buffer.com/resources/copywriting-formulas/",
        "likes": 420
    }

我无法解释为什么我在向用户模式添加任何新内容时收到此验证错误。

这是我的主要路由器代码:-

blogRouter.post('/', async (request, response) => {
    const blog = new Blog(request.body)

    if (blog.author === undefined || blog.title === undefined)
        return response.status(400).json({
            error: "name or title missing!"
        })

    //temporary get the first user from the Users db
    const userDB = await User.find({});
    //Get the first available user in db
    const currentUser = userDB[0]._id;

    console.log('CUrrrent post user: ', currentUser);

    const newBlog = new User({
        title: request.body.title,
        author: request.body.author,
        url: request.body.url,
        likes: request.body.likes || 0,
        user: currentUser
    })

    try {
        const newEntry = await newBlog.save()
        response.status(200).json(newEntry);
    } catch (error) {
        logger.error(error.message);
    }
})

我的博客架构:-

const blogSchema = new mongoose.Schema({
  title: String,
  author: String,
  url: String,
  likes: {
    type: Number,
    default: 0
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
})

blogSchema.set('toJSON', {
  transform: (document, returnedObject) => {
    returnedObject.id = returnedObject._id.toString()
    delete returnedObject._id
    delete returnedObject.__v
  }
})

module.exports = mongoose.model('Blog', blogSchema)

这是我的用户架构:-

var uniqueValidator = require('mongoose-unique-validator');

const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        minLength: 3,
        unique: true
    },
    name: {
        type: String,
        required: true
    },
    passwordHash: {
        type: String,
        required: true
    }
})

userSchema.plugin(uniqueValidator, {message: 'username already taken. {VALUE} not available.'});

userSchema.set('toJSON', {
    transform: (document, returnedObject) => {
        returnedObject.id = returnedObject._id.toString()
        delete returnedObject._id
        delete returnedObject.__v
        delete returnedObject.passwordHash
    }
})

const User = mongoose.model('User', userSchema);
module.exports = User

您应该在创建新的 Blog 文档时更改型号名称:

  const newBlog = new Blog({
    title: request.body.title,
    author: request.body.author,
    url: request.body.url,
    likes: request.body.likes || 0,
    user: currentUser,
  });

此外,一个好的做法是在检索第一个用户之前检查数据库中是否有任何用户。 这是为了避免可能的索引越界异常:

const userDB = await User.find({});
if (userDB.length > 0) {
    const currentUser = userDB[0]._id;
    ...