如何在更新猫鼬上设置_id参考

时间:2019-06-24 20:09:49

标签: node.js mongodb express mongoose

这是我的模特。

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

我不确定自己在做什么错。

1 个答案:

答案 0 :(得分:1)

您有错字,请在用户中使用:而不是=

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