首页 > 解决方案 > 如何在更新猫鼬上设置 _id 引用

问题描述

这是我的模型。

const mongoose = require('mongoose');

const schema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    brandName: {
        type: String,
        required: true
    },
    user: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
})

module.exports = mongoose.model('Food', schema);

我想将 userId 保存为食物集合的参考。

const newFood = new Food({
    _id: new mongoose.Types.ObjectId,
    brandName: req.body.brandName,
    user = mongoose.Types.ObjectId(req.body.userId),
})

现在我收到了这个控制台错误。

    user = mongoose.Types.ObjectId(req.body.userId),
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    SyntaxError: Invalid shorthand property initializer

我不确定我做错了什么。

标签: node.jsmongodbexpressmongoose

解决方案


你有一个错字,使用:而不是=在用户

user: mongoose.Types.ObjectId(req.body.userId)

推荐阅读