node.js - 将 Mongo/Mongoose 对象保存到另一个模型中

标签 node.js mongodb express mongoose schema

我有一个如下所示的 Mongo 对象:

var foodSchema = new mongoose.Schema({
   name:      { type: String, required: false, unique: true },
   image:     { type: String, required: false, unique: true },
});

这个想法是能够为用户保存“食物”对象。 (数据来自种子文件。)

因此,如果进入上述模型的数据是:

name: tacos, 
image: tacos.gif 

我想要做的是然后将该数据保存到用户模型中。 最好的方法是在用户模型中拥有一个字段来保存数据吗? (保存到最后两个字段)如:

var UserSchema = new mongoose.Schema({
    username: String,
    password: String,
    foodName1: String,
    foodImage1: String, 
});

对我来说,这似乎是我在两个不同的模型中保存了两次数据。这是处理这个问题的正确方法吗?或者是否有更好的方法将食物数据存储在用户模型中

最佳答案

你可以将 foodName1: String, foodImage1: String 替换为:

food: {id: { type: Schema.Types.ObjectId, ref: 'foodSchema'}

当你检索 foodSchema 后,使用 populate https://mongoosejs.com/docs/populate.html

如果您需要多个 foodSchema

food: [{id: { type: Schema.Types.ObjectId, ref: 'foodSchema'}]

为了保存,只需创建食物对象并放在现有用户或新创建的用户上:

let user = new UserSchema({'user info here'})
let food = new foodSchema({name: 'test',image: 'test'});
user.food = food
user.save().then(() => {

})

或者将食物推送到现有用户的食物数组中:

UserSchema.findById(req.body.id).exec((err, docc) => {
                docc.food.push(food)
                docc.save((err, result) => {
                    if (err)
                        res.sendStatus(500);
                    res.sendStatus(200);
                })
            })

否则我们可以只添加食物对象的 _id,但它不太直观

关于node.js - 将 Mongo/Mongoose 对象保存到另一个模型中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54438939/

相关文章:

node.js - google.gmail() 给出错误 TypeError : google. gmail 不是函数?

node.js - 如何杀死 exec 在 Windows 上运行的子进程?

python - 从主机连接到运行 MongoDB 的 Docker 容器

javascript - 将 JSON.Stringified 数据插入 MongoDB

java - 如何在 mongodb 和 Java 中 $and 两个文档?

python - Python 重新编码 JSON 文件

javascript - 将 JSON 传递给 Jade 并使用相同的数据进行 API 访问

node.js - Puppeteer 不渲染存储在 AWS S3 上的图像

node.js - YUI 压缩机在 PhpStorm 中给出未处理的 'error' 事件

node.js - Angular <app-root> 在 Node View 中无法识别