Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何在另一个模型中创建新模型?_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js 如何在另一个模型中创建新模型?

Node.js 如何在另一个模型中创建新模型?,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有一个TweetModel,我需要在里面创建RatingModel,RatingModel必须有一个相同的TweetModel id,因为我想链接它们以便进一步删除。 也许还有其他的方法来给猫鼬的帖子打分。 我将非常感谢你的帮助 const tweet = await TweetModel.create({ text: req.body.text, images: req.body.images, user: user._id, rating:

我有一个TweetModel,我需要在里面创建RatingModel,RatingModel必须有一个相同的TweetModel id,因为我想链接它们以便进一步删除。 也许还有其他的方法来给猫鼬的帖子打分。 我将非常感谢你的帮助

const tweet = await TweetModel.create({
      text: req.body.text,
      images: req.body.images,
      user: user._id,
      rating: ..., // => {retweets[], likes[]}
    })
    tweet.save()


假设您已经知道如何创建模式,您可以为您的tweet和评级创建两种不同的模式。这将创建两个单独的集合,这样将更易于管理

const { text, images } = req.body

const objectId = new mongoose.Types.ObjectId() //create a objectId first.

await TweetModel.updateOne({ _id }, { text, images, user: user._id }, { upsert: true })
await RatingModel.updateOne(....)
我们在这里使用的updateOne带有
{upsert:true}
选项,如果记录
\u id
不存在,我们将在其中创建一个新记录

你将能够很容易地获得评级与

更多关于
{upsert:true}
-

奖金 如果您想在一半的时间内创建记录

const [ tweet, rating ] = await Promise.all([
      TweetModel.updateOne({ _id }, { text, images, user: user._id }, { upsert: true })
      RatingModel.updateOne(....)
])
使用Promise.all,您可以同时执行两个更新请求

奖金2 如果您想在tweet中填充评级,请将其添加到您的模式中

TweetModel.virtual('rating', {
  ref: 'Rating',
  localField: '_id',
  foreignField: '_id',
});
滚动以填充-