[英]How to add save another Schema data to a model?
我在Mongodb v3.4.3中使用貓鼬
下面是我的圖像模型代碼
const mongoose = require("mongoose");
const CoordinateSchema = require("./coordinate");
const ImageSchema = new mongoose.Schema({
image_filename: {
type: String,
required: true
},
image_url: {
type: String,
required: true
},
coordinates: [CoordinateSchema],
});
下面是我的CoordinateSchema代碼
const mongoose = require("mongoose");
const CoordinateSchema = new mongoose.Schema({
coordinates : {
type: Array,
default: [],
}
});
module.exports = CoordinateSchema;
下面是我在Express上運行的api js代碼,
router.post('/receiveCoordinates.json', (req, res, next) => {
Image.findOneAndUpdate({image_filename:req.body.file_name}).then((image) => {
})
});
如何完成此代碼,以便將坐標數據存儲在Image模型中。
謝謝。
UPDATE
要更新findOneAndUpdate內部的坐標,只需檢查返回的文檔是否未定義(這意味着未找到您的圖像)。 修改您的api.js代碼,如下所示:
router.post('/receiveCoordinates.json', (req, res, next) => {
Image.findOneAndUpdate({image_filename:req.body.file_name}).then((image) => {
if (!image) return Promise.reject(); //Image not found, reject the promise
image.where({_id: parent.children.id(_id)}).update({coordinates: req.body.coordinates}) //Needs to be an array
.then((coords) => {
if (!coords) return Promise.reject();
//If you reach this point, everything went as expected
});
}).catch(() => {
console.log('Error occurred');
);
});
這是我的猜測,為什么它不起作用。
在ImageSchema
,您正在嵌套一個 CoordinateSchema
數組 。 但是CoordinateSchema是一個已經包含數組的文檔。
這可能不是您想要的。 如果您使用的是貓鼬版本4.2.0或更高版本 ,則可以將CoordinateSchema嵌套在ImageSchema中作為單個文檔。 像這樣重新編寫ImageSchema:
// ...
const ImageSchema = new mongoose.Schema({
// ...
coordinates: CoordinateSchema,
});
如果這不起作用或無法解決您的問題,請告訴我們,以便我們共同努力尋找解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.