乐闻世界logo
搜索文章和话题

How to save array of objects in mongoose

1个答案

1

In Mongoose, saving object arrays typically involves the following steps:

1. Define Schema

First, define a Mongoose Schema to map to MongoDB documents. If the array you're storing contains objects, define these objects as subdocuments within the Schema.

Here's an example: Suppose we want to save a user with multiple addresses, each address being an object containing street, city, and zip code:

javascript
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const addressSchema = new Schema({ street: String, city: String, zipCode: String }); const userSchema = new Schema({ name: String, addresses: [addressSchema] // This defines an array of objects }); const User = mongoose.model('User', userSchema);

2. Create and Save Documents

After defining the Schema, create a new instance of the Mongoose model and populate the array with objects. Then, save the document to MongoDB using .save().

javascript
const user = new User({ name: '张三', addresses: [ { street: '123 花园路', city: '上海', zipCode: '200000' }, { street: '456 光明路', city: '北京', zipCode: '100000' } ] }); user.save(function(err) { if (err) return console.error(err); console.log('User and addresses saved'); });

3. Update Arrays in Documents

To add more addresses or modify existing ones in an existing document, use .push() to add new addresses or directly modify the array elements and save.

javascript
User.findById(userId, function(err, user) { if (err) return console.error(err); user.addresses.push({ street: '789 新街口', city: '南京', zipCode: '210000' }); user.save(function(err) { if (err) return console.error(err); console.log('Address added'); }); });

4. Use Mongoose's Advanced Features

Mongoose offers methods for handling arrays easily, including MongoDB operators like $push and $pull, which can be used directly in update operations to efficiently modify arrays.

javascript
User.findByIdAndUpdate( userId, { $push: { addresses: { street: '1010 长江路', city: '武汉', zipCode: '430000' } }}, function(err, user) { if (err) return console.error(err); console.log('New address added via $push'); } );

By following these steps, you can effectively manage and operate on arrays containing objects in Mongoose. This is very useful for handling data with complex structures.

2024年6月29日 12:07 回复

你的答案