基本上,我有一个猫鼬模式,默认情况下,每次用户创建帐户时都会创建一个猫鼬模式。此架构在对象内部具有一个数组,该数组基本上是帖子。我正在尝试在此数组中插入数据,但无法正常工作,而且我无法通过阅读文档来弄清楚。
我尝试使用$ set $ addToSet和$ push,但没有使它们起作用。
模型:
'use strict';
const mongoose = require('mongoose');
const { Schema } = mongoose;
const trackingPostSchema = new Schema({
uuid: {
type: String,
unique: true,
},
post: [{
foodUuid: String,
pictureUrl: String,
foodName: String,
description: String,
calories: Number,
eatenAt: {
type: Date,
default: Date.now()
},
mealTime: String, //breakfast, lunch, dinner
}]
});
const trackingPost = mongoose.model('trackingPost', trackingPostSchema);
module.exports = trackingPost;
还有我要用来插入的函数:
async function createPosts(req, res){
const postData = {...req.body };
const foodUuid = uuidV4();
const { claims: uuid } = req;
try{
await validate(postData);
}catch(e){
return res.status(400).send(e);
}
try{
const filter = {
Uuid : uuid,
}
const data = {
$push: {
post: {
foodUuid,
foodName: postData.foodName,
description: postData.description,
calories: postData.calories,
mealTime: postData.mealTime
},
},
};
await trackingPostModel.findOneAndUpdate(filter, data);
return res.status(201).send();
}catch(e){
return res.status(500).send(e);
}
}
插入数据的功能不起作用。我如何使它工作?