我有一个如下所示的 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/